package com.revoapp.calendar.dialogs;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Handler;
import android.text.InputFilter;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.revoapp.api.database.calendar.pojo.Events;
import com.revoapp.calendar.DayActivity;
import com.revoapp.calendar.MonthActivity;
import com.revoapp.calendar.WeekActivity;
import com.revoapp.calendarapp.R;
import com.revoapp.calendar.components.InputFilterRange;
import com.revoapp.calendar.components.RevoImageButton;
import com.revoapp.calendar.database.DatabaseHandler;
import com.revoapp.calendar.helper.ThemeHelper;
import com.revoapp.calendar.service.EventAlarmServices;

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

public class AddEventDialog extends Dialog {
    private EditText title;
    private Button next;
    private int numberOfScreen = -1;

    private ArrayList<String> data;

    private MonthActivity mAct;
    private WeekActivity wAct;
    private DayActivity dAct;
    private View viewEventAdded;

    private Context context;
    private EditText hoursTV, minutesTV;
    private Button amPm;
    private int hours;
    private int minutes;
    private boolean dayTim = false;
    private boolean is24Hours;
    private boolean hpDown, hmDown, mpDown, mmDown;
    private Handler mHandler;
    private RelativeLayout timePickerLayout;
    private InputMethodManager imm;
    private Toast toast;
    private int orientation;

    public AddEventDialog(Context context, Activity act) {
        super(context, R.style.Theme_CustomDialog);

        setContentView(R.layout.dialog_add_event);

        this.context = context;

        View view = findViewById(R.id.dialogMainLayout);
        if (view != null)
            view.setBackgroundResource(ThemeHelper.get_dialogbox_backgroud_add_event());

        setCanceledOnTouchOutside(true);

        if (act.getClass().equals(MonthActivity.class))
            mAct = (MonthActivity) act;
        if (act.getClass().equals(WeekActivity.class))
            wAct = (WeekActivity) act;
        if (act.getClass().equals(DayActivity.class))
            dAct = (DayActivity) act;

        title = (EditText) findViewById(R.id.title);
        title.setHint(R.string.title);
        numberOfScreen = 0;
        title.requestFocus();

        next = (Button) findViewById(R.id.next_dialog);
        next.setOnClickListener(listener);
        next.setCompoundDrawablesWithIntrinsicBounds(null, context.getResources().getDrawable(ThemeHelper.get_icon100_arrow_right()), null, null);

        Button exit = (Button) findViewById(R.id.previous_dialog);
        exit.setOnClickListener(listener);
        exit.setCompoundDrawablesWithIntrinsicBounds(null, context.getResources().getDrawable(ThemeHelper.get_icon100_cancel()), null, null);

        Time time = new Time();
        time.setToNow();

        LayoutInflater inflater = getLayoutInflater();

        viewEventAdded = inflater.inflate(R.layout.toast_view,
                (ViewGroup) findViewById(R.id.toast_layout_root));
        viewEventAdded.setBackgroundResource(ThemeHelper.get_background_toast());

        toast = new Toast(context);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(viewEventAdded);

        data = new ArrayList<String>();

        imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
            }
        });

        timePickerLayout = (RelativeLayout) findViewById(R.id.include1);
        init();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    public AddEventDialog(Context context, Activity act, int numOfScreen, ArrayList<String> savedData, String savedTitle) {
        super(context, R.style.Theme_CustomDialog);

        setContentView(R.layout.dialog_add_event);

        this.context = context;

        View view = findViewById(R.id.dialogMainLayout);
        if (view != null)
            view.setBackgroundResource(ThemeHelper.get_dialogbox_backgroud_add_event());

        setCanceledOnTouchOutside(true);

        if (act.getClass().equals(MonthActivity.class))
            mAct = (MonthActivity) act;
        if (act.getClass().equals(WeekActivity.class))
            wAct = (WeekActivity) act;
        if (act.getClass().equals(DayActivity.class))
            dAct = (DayActivity) act;

        title = (EditText) findViewById(R.id.title);
        title.setHint(R.string.title);
        numberOfScreen = numOfScreen;
        title.requestFocus();

        next = (Button) findViewById(R.id.next_dialog);
        next.setOnClickListener(listener);
        next.setCompoundDrawablesWithIntrinsicBounds(null, context.getResources().getDrawable(ThemeHelper.get_icon100_arrow_right()), null, null);

        Button exit = (Button) findViewById(R.id.previous_dialog);
        exit.setOnClickListener(listener);
        exit.setCompoundDrawablesWithIntrinsicBounds(null, context.getResources().getDrawable(ThemeHelper.get_icon100_cancel()), null, null);

        Time time = new Time();
        time.setToNow();

        LayoutInflater inflater = getLayoutInflater();

        viewEventAdded = inflater.inflate(R.layout.toast_view,
                (ViewGroup) findViewById(R.id.toast_layout_root));
        viewEventAdded.setBackgroundResource(ThemeHelper.get_background_toast());

        toast = new Toast(context);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(viewEventAdded);

        data = new ArrayList<String>();
        data = savedData;

        imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
            }
        });

        timePickerLayout = (RelativeLayout) findViewById(R.id.include1);
        init();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        showViews();
        title.setText(savedTitle);
    }

    private View.OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if (arg0.getId() == R.id.next_dialog) {
                data.add(numberOfScreen, title.getText().toString());
                numberOfScreen++;
            }
            if (arg0.getId() == R.id.previous_dialog) {
                TextView text = (TextView) viewEventAdded.findViewById(R.id.text);
                text.setText(R.string.event_not_added);
                ImageView iv = (ImageView) viewEventAdded.findViewById(R.id.image);
                iv.setBackgroundResource(ThemeHelper.get_icon200_cancel());
                toast.setDuration(Toast.LENGTH_SHORT);
                toast.show();
                numberOfScreen = 0;
                dismiss();
            }

            showViews();
        }
    };

    private void showViews() {
        switch (numberOfScreen) {
            case 1:
                data.add(title.getText().toString());
                title.setText("");
                title.setHint(R.string.message);
                title.setVisibility(View.VISIBLE);
                timePickerLayout.setVisibility(View.INVISIBLE);
                break;
            case 2:
                data.add(title.getText().toString());
                title.setText("");
                title.setVisibility(View.INVISIBLE);
                next.setText(R.string.add_event2);
                next.setCompoundDrawablesWithIntrinsicBounds(null, context.getResources().getDrawable(ThemeHelper.get_icon100_ok()), null, null);
                timePickerLayout.setVisibility(View.VISIBLE);
                InputMethodManager imm =
                        (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(hoursTV.getWindowToken(), 0);
                break;
            case 4:
                data.add(title.getText().toString());
                title.setText("");
                title.setVisibility(View.INVISIBLE);
                next.setText(R.string.add_event2);
                next.setCompoundDrawablesWithIntrinsicBounds(null, context.getResources().getDrawable(ThemeHelper.get_icon100_ok()), null, null);
                timePickerLayout.setVisibility(View.INVISIBLE);
                break;
            case 3:
                TextView text = (TextView) viewEventAdded.findViewById(R.id.text);
                text.setText(R.string.event_added);
                ImageView iv = (ImageView) viewEventAdded.findViewById(R.id.image);
                iv.setBackgroundResource(ThemeHelper.get_icon200_ok());
                toast.show();
                addEvent();
                numberOfScreen = 0;
                dismiss();
                break;
        }
    }

    private void startAlarmServices() {
        Intent mServiceIntent = new Intent(context, EventAlarmServices.class);
        mServiceIntent.setAction(EventAlarmServices.CREATE);

        context.startService(mServiceIntent);
    }

    private void addEvent() {
        DatabaseHandler db = new DatabaseHandler(context);
        Events event = new Events();
        event.setDate(getDate());
        if (data.size() >= 1)
            event.setTitle(data.get(0));
        if (data.size() > 1)
            event.setMessage(data.get(1));

        db.addEvent(event);
        db.closeDB();
        if (mAct != null)
            mAct.refreshView();
        if (wAct != null)
            wAct.refreshView();
        if (dAct != null)
            dAct.refreshView();
        startAlarmServices();
    }

    private long getDate() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, MonthActivity.currentYear);
        cal.set(Calendar.MONTH, MonthActivity.currentMonth);
        cal.set(Calendar.DAY_OF_MONTH, MonthActivity.selectedDay);

        int h, m;
        h = Integer.valueOf(hoursTV.getText().toString());
        m = Integer.valueOf(minutesTV.getText().toString());
        if (!is24Hours) {
            if (dayTim && h != 12) {
                h += 12;
            }
        }

        cal.set(Calendar.HOUR_OF_DAY, h);
        cal.set(Calendar.MINUTE, m);
        return cal.getTimeInMillis() / 1000;
    }

    private void init() {
        is24Hours = DateFormat.is24HourFormat(context);
        Calendar time = Calendar.getInstance();

        Calendar cal = Calendar.getInstance();
        hours = cal.get(Calendar.HOUR_OF_DAY);
        if (!is24Hours) {
            if (hours > 12)
                hours -= 12;
        }

        minutes = time.get(Calendar.MINUTE);

        mHandler = new Handler();

        RevoImageButton hoursPlus = (RevoImageButton) findViewById(R.id.hours_plus);
        hoursPlus.setBackgroundResource(ThemeHelper.get_button_selector());
        hoursPlus.setImageResource(ThemeHelper.get_icon50_plus());
        hoursPlus.setOnClickListener(hoursListener);
        hoursPlus.setSampleLongpress(this);
        hoursPlus.setOnLongClickListener(longClickListener);

        RevoImageButton hoursMinus = (RevoImageButton) findViewById(R.id.hours_minus);
        hoursMinus.setBackgroundResource(ThemeHelper.get_button_selector());
        hoursMinus.setImageResource(ThemeHelper.get_icon50_minus());
        hoursMinus.setOnClickListener(hoursListener);
        hoursMinus.setSampleLongpress(this);
        hoursMinus.setOnLongClickListener(longClickListener);

        RevoImageButton minutesPlus = (RevoImageButton) findViewById(R.id.minutes_plus);
        minutesPlus.setBackgroundResource(ThemeHelper.get_button_selector());
        minutesPlus.setImageResource(ThemeHelper.get_icon50_plus());
        minutesPlus.setOnClickListener(minutesListener);
        minutesPlus.setSampleLongpress(this);
        minutesPlus.setOnLongClickListener(longClickListener);

        RevoImageButton minutesMinus = (RevoImageButton) findViewById(R.id.minutes_minus);
        minutesMinus.setBackgroundResource(ThemeHelper.get_button_selector());
        minutesMinus.setImageResource(ThemeHelper.get_icon50_minus());
        minutesMinus.setOnClickListener(minutesListener);
        minutesMinus.setSampleLongpress(this);
        minutesMinus.setOnLongClickListener(longClickListener);

        hoursTV = (EditText) findViewById(R.id.hours);
        hoursTV.setCursorVisible(false);
        hoursTV.setText(String.valueOf(hours));
        hoursTV.setOnTouchListener(clearTextView);
        hoursTV.setBackgroundDrawable(null);
        hoursTV.setOnEditorActionListener(editorListener);

        minutesTV = (EditText) findViewById(R.id.minutes);
        minutesTV.setCursorVisible(false);
        setMinutes();
        minutesTV.setOnTouchListener(clearTextView);
        minutesTV.setBackgroundDrawable(null);
        minutesTV.setOnEditorActionListener(editorListener);

        amPm = (Button) findViewById(R.id.am_pm);
        amPm.setBackgroundResource(ThemeHelper.get_button_selector());

        setAM_PM();

        if (is24Hours)
            amPm.setVisibility(View.INVISIBLE);
        amPm.setOnClickListener(dayTime);

        if (is24Hours)
            hoursTV.setFilters(new InputFilter[]{new InputFilterRange("0", "23")});
        else
            hoursTV.setFilters(new InputFilter[]{new InputFilterRange("1", "12")});
        minutesTV.setFilters(new InputFilter[]{new InputFilterRange("0", "59")});
    }

    private void setAM_PM() {
        if (amPm != null) {
            if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) > 11) {
                amPm.setText(R.string.pm);
                dayTim = true;
            } else
                amPm.setText(R.string.am);
        }
    }

    private void setMinutes() {
        if (minutes < 10)
            minutesTV.setText("0" + String.valueOf(minutes));
        else
            minutesTV.setText(String.valueOf(minutes));
    }

    private OnEditorActionListener editorListener = new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == 6) {
                if (v == minutesTV) {
                    if (minutesTV != null && minutesTV.length() > 0) {
                        minutes = Integer.valueOf(v.getText().toString());
                        if (minutes < 10)
                            minutesTV.setText("0" + String.valueOf(minutes));
                    } else
                        v.setText(String.valueOf(minutes));
                } else if (v == hoursTV) {
                    if (hoursTV != null && hoursTV.length() > 0) {
                        hours = Integer.valueOf(v.getText().toString());
                    } else
                        v.setText(String.valueOf(hours));
                }
            }
            return false;
        }
    };

    private OnLongClickListener longClickListener = new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            if (v.getId() == R.id.hours_plus) {
                hpDown = true;
                hmDown = false;
                mpDown = false;
                mmDown = false;
            } else if (v.getId() == R.id.hours_minus) {
                hpDown = false;
                hmDown = true;
                mpDown = false;
                mmDown = false;
            } else if (v.getId() == R.id.minutes_plus) {
                hpDown = false;
                hmDown = false;
                mpDown = true;
                mmDown = false;
            } else if (v.getId() == R.id.minutes_minus) {
                hpDown = false;
                hmDown = false;
                mpDown = false;
                mmDown = true;
            }

            mHandler.post(mRunnable);
            return true;
        }
    };

    private final Runnable mRunnable = new Runnable() {
        public void run() {
            if (hpDown) {
                hours++;
                if (is24Hours) {
                    if (hours >= 24)
                        hours = 0;
                } else {
                    if (hours >= 13)
                        hours = 1;
                }

                hoursTV.setText(String.valueOf(hours));
                mHandler.postDelayed(this, 200);
            }
            if (hmDown) {
                hours--;
                if (is24Hours) {
                    if (hours <= 0)
                        hours = 23;
                } else {
                    if (hours <= 0)
                        hours = 12;
                }

                hoursTV.setText(String.valueOf(hours));
                mHandler.postDelayed(this, 200);
            }
            if (mpDown) {
                minutes++;
                if (minutes > 59)
                    minutes = 0;

                setMinutes();
                mHandler.postDelayed(this, 200);
            }
            if (mmDown) {
                minutes--;
                if (minutes < 0)
                    minutes = 59;

                setMinutes();
                mHandler.postDelayed(this, 200);
            }
        }
    };

    public void cancelLongPress() {
        hpDown = false;
        hmDown = false;
        mpDown = false;
        mmDown = false;
    }

    private View.OnClickListener hoursListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.hours_plus) {
                hours++;

                if (is24Hours) {
                    if (hours >= 24)
                        hours = 0;
                } else {
                    if (hours >= 13)
                        hours = 1;
                }

                hoursTV.setText(String.valueOf(hours));
            } else if (v.getId() == R.id.hours_minus) {
                hours--;

                if (is24Hours) {
                    if (hours <= 0)
                        hours = 23;
                } else {
                    if (hours <= 0)
                        hours = 12;
                }

                hoursTV.setText(String.valueOf(hours));
            }
        }
    };

    private View.OnClickListener minutesListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.minutes_plus) {
                minutes++;

                if (minutes > 59)
                    minutes = 0;

                setMinutes();
            } else if (v.getId() == R.id.minutes_minus) {
                minutes--;

                if (minutes < 0)
                    minutes = 59;

                setMinutes();
            }
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
        dismiss();
    }

    private OnTouchListener clearTextView = new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (v.getId() == R.id.hours) {
                hoursTV.setText("");
            } else if (v.getId() == R.id.minutes) {
                minutesTV.setText("");
            }

            return false;
        }
    };

    private View.OnClickListener dayTime = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (dayTim) {
                amPm.setText(R.string.am);
                dayTim = false;
            } else {
                amPm.setText(R.string.pm);
                dayTim = true;
            }
        }
    };

    @Override
    public void show() {
        super.show();
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(getWindow().getAttributes());

        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindow().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int width = displaymetrics.widthPixels;


        orientation = getContext().getResources().getConfiguration().orientation;
        if(orientation == Configuration.ORIENTATION_LANDSCAPE){
            lp.height = (R.dimen.dialog_add_event_size);
            lp.width = width - 100;
        } else if (orientation == Configuration.ORIENTATION_PORTRAIT){
            lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            lp.width = width;
        }


        lp.x = 0;
        lp.y = -100;
        getWindow().setAttributes(lp);
    }

    public int getNumberOfScreen() {
        return numberOfScreen;
    }

    public ArrayList<String> getData() {
        return data;
    }

    public String getTitle() {
        return title.getText().toString();
    }

}