package com.example.calendaryapp;


import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MiercolesAgenda extends AppCompatActivity {
    public static final int ADD_NOTE_REQUEST= 1;
    private NoteViewModel noteViewModel;
    private ArrayList<Integer> listOfClicks = new ArrayList<Integer>();
    private TimeAlarmPicker alarmModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_miercoles_agenda);

        FloatingActionButton buttonAddNote = findViewById(R.id.button_add_note);
        buttonAddNote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MiercolesAgenda.this, AddNoteActivity.class);
                startActivityForResult(intent, ADD_NOTE_REQUEST);
            }
        });


        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);

        final NoteAdapter adapter = new NoteAdapter();
        recyclerView.setAdapter(adapter);
        alarmModel = new TimeAlarmPicker();
        adapter.setOnItemClickListener(new OnItemClickListenerW() {
            public void onItemClick(int position) {
                Note notaclickeada = adapter.getNoteAt(position);
                if(!listOfClicks.contains(notaclickeada.getPriority())){
                    startAlarm(alarmModel.onTimeSet(notaclickeada.getPriority()-20),notaclickeada.getPriority());
                    Toast.makeText(MiercolesAgenda.this, "Alarma para este bloque "+notaclickeada.getPriority(), Toast.LENGTH_SHORT).show();

                    listOfClicks.add(notaclickeada.getPriority());
                }
                else{
                    cancelAlarm(notaclickeada.getPriority());
                    Toast.makeText(MiercolesAgenda.this, "Alarma Desactivada+"+notaclickeada.getPriority(), Toast.LENGTH_SHORT).show();
                    listOfClicks.remove(listOfClicks.indexOf(notaclickeada.getPriority()));
                }


            }

        });







        noteViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
        noteViewModel.getAllNotes(2).observe(this, new Observer<List<Note>>() {
            @Override
            public void onChanged(@Nullable List<Note> notes) {
                //update RecyclerView solo se llama si es que la actividad esta siendo usada evitando memory leakeage
                //Toast.makeText(LunesAgenda.this, "onChanged", Toast.LENGTH_SHORT).show();
                adapter.setNotes(notes);

            }
        });
        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
                ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                noteViewModel.delete(adapter.getNoteAt(viewHolder.getAdapterPosition()));
                Toast.makeText(MiercolesAgenda.this, "Note deleted", Toast.LENGTH_SHORT).show();
            }
        }).attachToRecyclerView(recyclerView);
    }
    private void startAlarm(Calendar c,int alarmNumber) {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, AlertReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this,alarmNumber, intent, 0);

        if (c.before(Calendar.getInstance())) {
            c.add(Calendar.DATE, 1);
        }

        alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
    }

    public void cancelAlarm(int alarmNumberD) {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, AlertReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, alarmNumberD, intent, 0);

        alarmManager.cancel(pendingIntent);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == ADD_NOTE_REQUEST && resultCode == RESULT_OK) {
            String title = data.getStringExtra(AddNoteActivity.EXTRA_TITLE);
            String description = data.getStringExtra(AddNoteActivity.EXTRA_DESCRIPTION);
            String sala = data.getStringExtra(AddNoteActivity.EXTRA_SALA);
            int priority = data.getIntExtra(AddNoteActivity.EXTRA_PRIORITY, 1)+20;
            String Bloque= "1-2";
            String Horario= "1-2";

            switch(priority){
                case 21: Bloque = "1-2";
                    Horario = "8:00-9:30";
                    break;
                case 22: Bloque = "3-4";
                    Horario = "9:45-11:15";
                    break;
                case 23: Bloque = "5-6";
                    Horario = "11:30-13:00";
                    break;
                case 24: Bloque = "7-8";
                    Horario = "14:00-15:30";
                    break;
                case 25: Bloque = "9-10";
                    Horario = "15:40-17:10";
                    break;
                case 26: Bloque = "11-12";
                    Horario = "17:20-18:50";
                    break;
                case 27: Bloque = "13-14";
                    Horario = "19:00-20:30";
                    break;

            }

            Note note = new Note(title, description, priority,Bloque,Horario,sala);
            noteViewModel.insert(note);

            Toast.makeText(this, "Note saved", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Note not saved", Toast.LENGTH_SHORT).show();// el result code sera cancel
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main_menu, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.delete_all_notes:
                noteViewModel.deleteAllNotes();
                Toast.makeText(this, "All notes deleted", Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}
