package com.example.ugotthis;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class TasksActivity extends AppCompatActivity implements View.OnClickListener {


    public static final String EXTRA_MESSAGE = "com.example.ugotthis Message";

    //Variable
    private final AppCompatActivity activity = TasksActivity.this;
    private ImageView nTask;
    Button btnDatePicker;
    EditText txtDate;
    ListView listTasks;
    private DatabaseHelper databaseHelper;
    private int mYear, mMonth, mDay;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tasks);

        btnDatePicker=(Button)findViewById(R.id.button_date);
        btnDatePicker.setOnClickListener(this);
        txtDate = (EditText)findViewById(R.id.editText_date);

        nTask = (ImageView)findViewById(R.id.imageView_add);
        nTask.setOnClickListener(this);

        Date c = Calendar.getInstance().getTime();
        System.out.println("Current time => " + c);

        SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
        String formattedDate = df.format(c);

        txtDate.setText(formattedDate);

        // Instantiate list view
        listTasks = (ListView)findViewById(R.id.listTask);

        listtasks();
    }

    @Override
    public void onClick(View v) {

        databaseHelper = new DatabaseHelper(activity);

        switch (v.getId()) {

            case R.id.imageView_add :{

                Intent taskActivity = new Intent(TasksActivity.this, NewTask.class);
                startActivity(taskActivity);
                break;
            }
            case R.id.button_date: {
                // Get Current Date
                final Calendar c = Calendar.getInstance();
                mYear = c.get(Calendar.YEAR);
                mMonth = c.get(Calendar.MONTH);
                mDay = c.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                        new DatePickerDialog.OnDateSetListener() {

                            @Override
                            public void onDateSet(DatePicker view, int year,
                                                  int monthOfYear, int dayOfMonth) {

                                String cMonth;
                                String cDay;

                                if (monthOfYear < 9) {
                                    cMonth = "0" + String.valueOf(monthOfYear + 1);
                                }
                                else {
                                    cMonth = String.valueOf(monthOfYear + 1);
                                }

                                if (dayOfMonth < 10) {
                                    cDay = "0" + String.valueOf(dayOfMonth);
                                }
                                else {
                                    cDay = String.valueOf(dayOfMonth);
                                }

                                txtDate.setText(cDay + "-" + cMonth + "-" + year);
                                listtasks();

                            }
                        }, mYear, mMonth, mDay);
                datePickerDialog.show();
                break;
            }
            default: {
                break;
            }
        }
    }

    // Load tasks to list view from database
    private void listtasks() {

        // Open database connection
        DatabaseHelper helper = new DatabaseHelper(this);

        SharedPreferences preferences = getSharedPreferences("MYPREFS", MODE_PRIVATE);
        int userID = preferences.getInt("user_id", 0);
        Log.d("User ID, Task list", String.valueOf(userID));

        String newDate = txtDate.getText().toString();

        // Get all tasks and put to a list
        List<Task> taskList =  helper.getAllTask(String.valueOf(userID), newDate);

        // Create an array list
        List<HashMap<String, String>> mapData = new ArrayList<HashMap<String, String>>();

        // Get task details from list and add to array list
        for (Task task : taskList) {

            Log.d("User ID, Array", String.valueOf(task.getId()));

            HashMap<String, String> map = new HashMap<String, String>();

            // Get other details and put to array list
            map.put("Id", String.valueOf(task.getId()));
            map.put("Date", String.valueOf(task.getDate()));
            map.put("State", String.valueOf(task.getActiveFlag()));
            map.put("Time", "Time: " + task.getTime());
            map.put("Title", task.getTitle());
            map.put("Description", task.getDescription());


            // Convert task state integer to string
            if (task.getActiveFlag() == 0) {
                map.put("State", "Uncompleted");
            }
            else if (task.getActiveFlag() == 1) {
                map.put("State", "Completed");
            }
            else if (task.getActiveFlag() == 2) {
                map.put("State", "Deleted");
            }



            mapData.add(map);
        }

        // Close database connection
        helper.close();

        // Keys used in Hashmap
        String[] from = {"Id", "Date", "State", "Title","Time","Description"};

        // IDs of views in list view layout
        int[] to = {R.id.hidden_id, R.id.hidden_date, R.id.txtState, R.id.txtTitle, R.id.txtTime, R.id.txtDescription};

        // Instantiating an adapter to store each items
        // R.layout.list_task defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), mapData, R.layout.list_task, from, to);

        // Getting a reference to listView from actual activity layout
        final ListView listView = (ListView)findViewById(R.id.listTask);

        Log.d("Adapter count", String.valueOf(adapter.getCount()));

        // Setting the adapter to the listView
        listView.setAdapter(adapter);
    }


    public void clickedEdit(View view) {
        LinearLayout lv = (LinearLayout) view.getParent().getParent();
        String id = ((TextView) lv.findViewById(R.id.hidden_id)).getText().toString();

        //creating and initializing an Intent object
        Intent intent = new Intent(this, EditTask.class);
        //attach the key value pair using putExtra to this intent
        intent.putExtra("TASK_ID", id);
        //starting the activity
        startActivity(intent);
    }

    public void clickedMessage(View view) {
        LinearLayout lv = (LinearLayout) view.getParent().getParent();
        String id = ((TextView) lv.findViewById(R.id.hidden_id)).getText().toString();
        String title = ((TextView) lv.findViewById(R.id.txtTitle)).getText().toString();
        String date = ((TextView) lv.findViewById(R.id.hidden_date)).getText().toString();
        String time = ((TextView) lv.findViewById(R.id.txtTime)).getText().toString();
        String description = ((TextView) lv.findViewById(R.id.txtDescription)).getText().toString();

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("sms:"));
        intent.putExtra("sms_body", "Reminder!" +
                " Title: " +  title +
                ". Date: " +  date +
                ". Time: " +  time + ". Message: ");
        startActivity(intent);
    }

    public void clickedDelete(View view) {
        LinearLayout lv = (LinearLayout) view.getParent().getParent();
        final String tID = ((TextView) lv.findViewById(R.id.hidden_id)).getText().toString();

        Log.d("Delete", tID);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure?")
                .setTitle("Confirm delete")
                .setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // CONFIRM
                        databaseHelper = new DatabaseHelper(activity);

                        Log.d("Delete", tID);
                        databaseHelper.deleteTask(Integer.parseInt(tID));
                        listtasks();
                    }
                })
                .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // CANCEL
                    }
                });
        // Create the AlertDialog object and return it
        builder.show();
    }
}
