package com.example.ugotthis;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.widget.DatePicker;
import android.widget.TimePicker;
import com.google.android.gms.maps.model.LatLng;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class EditTask extends AppCompatActivity implements View.OnClickListener {

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

    //Variable
    Button btnDatePicker, btnTimePicker, btnAddressPicker;
    EditText txtTitle, txtDescription, txtAddress, txtDate, txtTime;
    CheckBox cbState;
    private final AppCompatActivity activity = EditTask.this;
    private Button btnSave;
    private DatabaseHelper databaseHelper;
    private Task task;
    private int mYear, mMonth, mDay, mHour, mMinute;
    private String taskID;

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

        btnDatePicker = (Button)findViewById(R.id.button_date);
        btnTimePicker = (Button)findViewById(R.id.button_time);
        btnAddressPicker = (Button)findViewById(R.id.button_address);
        btnSave=(Button)findViewById(R.id.button_save);

        btnDatePicker.setOnClickListener(this);
        btnTimePicker.setOnClickListener(this);
        btnAddressPicker.setOnClickListener(this);
        btnSave.setOnClickListener(this);

        txtTitle = (EditText)findViewById(R.id.editText_title);
        txtDescription = (EditText)findViewById(R.id.editText_nDescription2);
        txtAddress = (EditText)findViewById(R.id.editText_address);
        txtDate = (EditText)findViewById(R.id.editText_date);
        txtTime = (EditText)findViewById(R.id.editText_time);
        cbState = (CheckBox)findViewById(R.id.chkEdit);

        //get the current intent
        Intent intent = getIntent();
        //get the attached extras from the intent
        //we should use the same key as we used to attach the data.
        taskID = intent.getStringExtra("TASK_ID");

        databaseHelper = new DatabaseHelper(activity);

        //Read task data
        readdata();
    }

    private void readdata() {

        Task task = new Task();
        task = databaseHelper.getTask(taskID);

        txtTitle.setText(task.getTitle());
        txtDescription.setText(task.getDescription());
        txtAddress.setText(task.getAddress());
        txtDate.setText(task.getDate());
        txtTime.setText(task.getTime());

        String state = String.valueOf(task.getActiveFlag());

        if (state.equals("1")) {
            cbState.setChecked(true);
        }
    }


    @Override
    public void onClick(View v) {

        task = new Task();

        switch (v.getId()) {

            case R.id.button_save: {

                String newTitle = txtTitle.getText().toString();
                String newDescription = txtDescription.getText().toString();
                String newAddress = txtAddress.getText().toString();
                String newDate = txtDate.getText().toString();
                String newTime = txtTime.getText().toString();

                if (newTitle.length() == 0) {
                    txtTitle.setError("Please enter Title !");
                } else {
                    if (newDescription.length() == 0) {
                        txtDescription.setError("Please enter Description !");
                    }
                    else {

                        if (newAddress.length() == 0) {
                            txtAddress.setError("Please Choose Address !");
                        }
                        else{
                            if (newDate.length() == 0) {
                                txtDate.setError("Please Choose Date !");
                            }
                            else{
                                if (newTime.length() == 0) {
                                    txtTime.setError("Please Choose Time !");
                                }
                                else{

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

                                    task.setId(Integer.parseInt(taskID));
                                    task.setUserId(userID);
                                    task.setTitle(newTitle);
                                    task.setDescription(newDescription);
                                    task.setAddress(newAddress);
                                    task.setDate(newDate);
                                    task.setTime(newTime);

                                    if(cbState.isChecked()) {
                                        task.setActiveFlag(1);
                                    }
                                    else {
                                        task.setActiveFlag(0);
                                    }

                                    databaseHelper.updateTask(task);

                                    Intent taskActivity = new Intent(EditTask.this, TasksActivity.class);
                                    startActivity(taskActivity);

                                }
                            }
                        }
                    }
                }
                break;
            }
            case R.id.button_address: {
                Log.d("Adress", "Clicked");

                String locationAddress = txtAddress.getText().toString();

                LatLng lt = getLocationFromAddress(this, locationAddress);
                Log.d("Lat", String.valueOf(lt.latitude));

                String uriBegin = "geo:" + lt.latitude + "," + lt.longitude;
                String query = lt.latitude + "," + lt.longitude + "(" + locationAddress + ")";
                String encodedQuery = Uri.encode(query);
                String uriString = uriBegin + "?q=" + encodedQuery + "&z=16";
                Uri uri = Uri.parse(uriString);
                Intent mapIntent = new Intent(android.content.Intent.ACTION_VIEW, uri);
                startActivity(mapIntent);

                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);

                            }
                        }, mYear, mMonth, mDay);
                datePickerDialog.show();
                break;
            }
            case R.id.button_time: {
                // Get Current Time
                final Calendar c = Calendar.getInstance();
                mHour = c.get(Calendar.HOUR_OF_DAY);
                mMinute = c.get(Calendar.MINUTE);

                // Launch Time Picker Dialog
                TimePickerDialog timePickerDialog = new TimePickerDialog(this,
                        new TimePickerDialog.OnTimeSetListener() {

                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay,
                                                  int minute) {

                                String cHour;
                                String cMinute;

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

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

                                txtTime.setText(cHour + ":" + cMinute);
                            }
                        }, mHour, mMinute, false);
                timePickerDialog.show();
                break;
            }
            default: {
                break;
            }
        }
    }

    public LatLng getLocationFromAddress(Context context, String strAddress) {

        Geocoder coder = new Geocoder(context);
        List<Address> address;
        LatLng p1 = null;

        try {
            // May throw an IOException
            address = coder.getFromLocationName(strAddress, 5);
            if (address == null) {
                return null;
            }

            Address location = address.get(0);
            p1 = new LatLng(location.getLatitude(), location.getLongitude() );

        } catch (IOException ex) {

            ex.printStackTrace();
            Toast.makeText(EditTask.this, "Invalid address!", Toast.LENGTH_LONG).show();
        }

        return p1;
    }

    private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
        String strAdd = "";
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        try {
            List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
            if (addresses != null) {
                Address returnedAddress = addresses.get(0);
                StringBuilder strReturnedAddress = new StringBuilder("");

                for (int i = 0; i <= returnedAddress.getMaxAddressLineIndex(); i++) {
                    strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                }
                strAdd = strReturnedAddress.toString();
                Log.w("My Current loction", strReturnedAddress.toString());
            } else {
                Log.w("My Current loction", "No Address returned!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.w("My Current loction", "Canont get Address!");
        }
        return strAdd;
    }
}

