package com.sudogeeks.talking_reminder;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import org.json.JSONObject;

import java.io.InputStream;
import java.util.Calendar;


/**\brief Class to read and parse reminder Data after receiving
 * This class parse the received reminder object and saves that in database and trigger alarm for that.
 */
public class ReminderReceiveActivity extends AppCompatActivity {
    private static final long milMinute = 60000L;
    private static final long milHour = 3600000L;
    private static final long milDay = 86400000L;
    private static final long milWeek = 604800000L;
    private static final long milMonth = 2592000000L;
    private Toolbar mToolbar;
    private EditText mTitleText;
    private TextView mDateText, mTimeText, mRepeatText, mRepeatNoText, mRepeatTypeText;
    private String mRepeat;
    private String mRepeatType;
    private String mRepeatNo;
    private Calendar mCalendar;
    private int mYear, mMonth, mHour, mMinute, mDay;
    private long mRepeatTime;
    private String mActive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive_reminder);
        Context context = this;

        mCalendar = Calendar.getInstance();
        mHour = mCalendar.get(Calendar.HOUR_OF_DAY);
        mMinute = mCalendar.get(Calendar.MINUTE);
        mYear = mCalendar.get(Calendar.YEAR);
        mMonth = mCalendar.get(Calendar.MONTH) + 1;
        mDay = mCalendar.get(Calendar.DATE);

        //by default
        mActive = "true";
        // Setup Toolbar
        mToolbar = findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle(R.string.activity_add_reminder_label);

        //Get the file from intent
        Intent intent = getIntent();
        Uri fileUri = intent.getData();
        StringBuilder reminderJson = new StringBuilder();
        if (intent.getType().equals("text/" + Utility.FILE_EXTENSION)) {
            try {
                InputStream in = getContentResolver().openInputStream(fileUri);
                int i;

                while ((i = in.read()) != -1)
                    reminderJson.append((char) i);
                //System.out.println("******************************************************************");
                //System.out.println(sb.toString());
                //System.out.println("******************************************************************");
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                JSONObject obj = new JSONObject(reminderJson.toString());
                //ReminderDO talkingReminder=new ReminderDO();
                mTitleText = findViewById(R.id.reminder_title);
                mDateText = findViewById(R.id.set_date);
                mTimeText = findViewById(R.id.set_time);
                mRepeatText = findViewById(R.id.set_repeat);
                mRepeatNoText = findViewById(R.id.set_repeat_no);
                mRepeatTypeText = findViewById(R.id.set_repeat_type);

                mRepeat = obj.getString("mRepeat");
                mRepeatType = obj.getString("mRepeatType");
                mRepeatNo = obj.getString("mRepeatNo");

                mTitleText.setText(obj.getString("mTitle"));
                mDateText.setText(obj.getString("mDate"));
                mTimeText.setText(obj.getString("mTime"));
                mRepeatText.setText("Every " + obj.getString("mRepeatNo") + " " + obj.getString("mRepeatType") + "(s)");
                mRepeatNoText.setText(obj.getString("mRepeatNo"));
                mRepeatTypeText.setText(obj.getString("mRepeatType"));


            } catch (Throwable t) {
                t.printStackTrace();
            }


            /*Intent senderIntent = new Intent(context, ReminderEditActivity.class);
            senderIntent.putExtra("received", true);
            senderIntent.putExtra("mTitle", "First Receive ReminderDO test");
            startActivity(senderIntent);*/
        }
    }

    /**
     * This method populates the ui as received and then saves the reminder to database.
     */
    public void saveSendReminder() {
        ReminderDatabase rb = new ReminderDatabase(this);

        // Creating ReminderDO
        int ID = rb.addReminder(new ReminderDO(mTitleText.getText().toString(), mDateText.getText().toString(), mTimeText.getText().toString(), mRepeat, mRepeatNoText.getText().toString(), mRepeatTypeText.getText().toString(), mActive));


        // Set up calender for creating the notification
        mCalendar.set(Calendar.MONTH, --mMonth);
        mCalendar.set(Calendar.YEAR, mYear);
        mCalendar.set(Calendar.DAY_OF_MONTH, mDay);
        mCalendar.set(Calendar.HOUR_OF_DAY, mHour);
        mCalendar.set(Calendar.MINUTE, mMinute);
        mCalendar.set(Calendar.SECOND, 0);

        // Check repeat type
        if (mRepeatType.equals("Minute")) {
            mRepeatTime = Integer.parseInt(mRepeatNo) * milMinute;
        } else if (mRepeatType.equals("Hour")) {
            mRepeatTime = Integer.parseInt(mRepeatNo) * milHour;
        } else if (mRepeatType.equals("Day")) {
            mRepeatTime = Integer.parseInt(mRepeatNo) * milDay;
        } else if (mRepeatType.equals("Week")) {
            mRepeatTime = Integer.parseInt(mRepeatNo) * milWeek;
        } else if (mRepeatType.equals("Month")) {
            mRepeatTime = Integer.parseInt(mRepeatNo) * milMonth;
        }

        // Create a new notification
        if (mActive.equals("true")) {
            if (mRepeat.equals("true")) {
                new AlarmReceiver().setRepeatAlarm(getApplicationContext(), mCalendar, ID, mRepeatTime);
            } else if (mRepeat.equals("false")) {
                new AlarmReceiver().setAlarm(getApplicationContext(), mCalendar, ID);
            }
        }

        // Create toast to confirm new reminder
        Toast.makeText(getApplicationContext(), "Saved",
                Toast.LENGTH_SHORT).show();

        onBackPressed();
    }

    // Creating the menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_receive_reminder, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            // On clicking the back arrow
            // Discard any changes
            case android.R.id.home:
                onBackPressed();
                return true;

            // On clicking save reminder button
            // Update reminder
            case R.id.save_reminder:
                saveSendReminder();


            default:
                return super.onOptionsItemSelected(item);
        }
    }

}
