package kr.co.hanwha.hifive.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;

import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.adapter.CalendarGridAdapter;
import kr.co.hanwha.hifive.data.model.CalendarData;
import kr.co.hanwha.hifive.util.HFDateUtil;
import kr.co.hanwha.hifive.view.HFToastView;

/**
 * Created by sanghoonkwon on 2018. 1. 18..
 */

public class HFCalendarDialog extends Dialog {
    private TextView mTextViewTitle;
    private RecyclerView mRecyclerView;
    private CalendarGridAdapter mCalendarGridAdapter;

    private int mCurrentYear;
    private int mCurrentMonth;
    private int mCurrentDate;

    private String mSelectDate;
    private OnDialogCallback mCallback;

    public HFCalendarDialog(@NonNull Context context) {
        super(context);
    }

    public HFCalendarDialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, themeResId);
    }

    public HFCalendarDialog(@NonNull Context context, @Nullable String selectDate, @Nullable OnDialogCallback callback) {
        super(context, R.style.DialogFadeAnim);
        setCancelable(false);
        this.mSelectDate = selectDate;
        this.mCallback = callback;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.dialog_hf_calendar);

        mTextViewTitle = (TextView) findViewById(R.id.title_textView);
        TextView textViewNegative = (TextView) findViewById(R.id.negative_textView);
        TextView textViewPositive = (TextView) findViewById(R.id.positive_textView);

        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mCalendarGridAdapter = new CalendarGridAdapter(onCalendarListener);
        mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 7));
        mRecyclerView.setAdapter(mCalendarGridAdapter);

        findViewById(R.id.previous_imageButton).setOnClickListener(onClickListener);
        findViewById(R.id.next_imageButton).setOnClickListener(onClickListener);
        textViewNegative.setOnClickListener(onClickListener);
        textViewPositive.setOnClickListener(onClickListener);


        mCurrentYear = Integer.parseInt(HFDateUtil.getDateFormatFromToday(HFDateUtil.FORMAT_YEAR));
        mCurrentMonth = Integer.parseInt(HFDateUtil.getDateFormatFromToday(HFDateUtil.FORMAT_MONTH));
        mCurrentDate = Integer.parseInt(HFDateUtil.getDateFormatFromToday(HFDateUtil.FORMAT_DAY));
        if (TextUtils.isEmpty(mSelectDate))
            mSelectDate = HFDateUtil.getDateFormatToday(HFDateUtil.FORMAT_TASK_DUEDATE_SERVER);

        // 키보드 보이기(UX)
        final EditText editText = (EditText) findViewById(R.id.editText);
        editText.requestFocus();
        editText.postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager input = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                input.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
            }
        }, 100);

        initData();
    }

    private void initData() {
        String monthDisplay = HFDateUtil.getDateFormat(mCurrentYear, mCurrentMonth, mCurrentDate, HFDateUtil.FORMAT_CALENDAR_MONTH_DISPLAY);

        mTextViewTitle.setText(monthDisplay);

        ArrayList<CalendarData> list = new ArrayList<>();
        int lastMonth = (mCurrentMonth == 1) ? 12 : mCurrentMonth - 1;
        int lastYear = (mCurrentMonth == 1) ? mCurrentYear - 1 : mCurrentYear;
        int lastMonthLastDay = HFDateUtil.getActualMaximum(lastYear, lastMonth);

        int weekday = HFDateUtil.getDayOfWeek(mCurrentYear, mCurrentMonth, 1);//이번달의 첫 요일 확인
        for (int i = 1; i < weekday; i++) {
            int month = lastMonth;
            int date = lastMonthLastDay - (weekday - i - 1);
            boolean isEnable = HFDateUtil.checkTwoWeeksFromToday(lastYear, month, date);
            boolean isSelected = HFDateUtil.checkSelectedDate(lastYear, month, date, mSelectDate);
            list.add(new CalendarData(month, date, isEnable, isSelected));
        }

        int currentMaximumDate = HFDateUtil.getActualMaximum(mCurrentYear, mCurrentMonth);//이번달의 마지막 날짜 확인(28, 29, 30, 31)
        for (int i = 1; i <= currentMaximumDate; i++) {
            int month = mCurrentMonth;
            int date = i;
            boolean isEnable = HFDateUtil.checkTwoWeeksFromToday(mCurrentYear, month, date);
            boolean isSelected = HFDateUtil.checkSelectedDate(mCurrentYear, month, date, mSelectDate);
            list.add(new CalendarData(month, date, isEnable, isSelected));
        }

        int weekdayLast = HFDateUtil.getDayOfWeek(mCurrentYear, mCurrentMonth, currentMaximumDate);//이번달의 마지막 요일 확인
        int nextMonth = (mCurrentMonth == 12) ? 1 : mCurrentMonth + 1;
        for (int i = 1; i <= 7 - weekdayLast; i++) {
            int month = nextMonth;
            int date = i;
            boolean isEnable = HFDateUtil.checkTwoWeeksFromToday(mCurrentYear, month, date);
            boolean isSelected = HFDateUtil.checkSelectedDate(mCurrentYear, month, date, mSelectDate);
            list.add(new CalendarData(month, date, isEnable, isSelected));
        }

        mCalendarGridAdapter.addItems(list);
        mCalendarGridAdapter.notifyDataSetChanged();
    }

    private void previousMonth() {
        if (mCurrentYear < 2000) return;

        if (mCurrentMonth == 1) {
            mCurrentYear -= 1;
            mCurrentMonth = 12;
        } else {
            mCurrentMonth -= 1;
        }
        initData();
    }

    private void nextMonth() {
        if (mCurrentYear > 2030) return;

        if (mCurrentMonth == 12) {
            mCurrentYear += 1;
            mCurrentMonth = 1;
        } else {
            mCurrentMonth += 1;
        }
        initData();
    }

    /**************************************************
     * Callback
     **************************************************/
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.previous_imageButton:
                    previousMonth();
                    break;
                case R.id.next_imageButton:
                    nextMonth();
                    break;
                case R.id.negative_textView:
                    HFCalendarDialog.this.dismiss();
                    break;
                case R.id.positive_textView:
                    if (mCallback != null) {
                        mCallback.onConfirm(mSelectDate);
                    }
                    HFCalendarDialog.this.dismiss();
                    break;
            }
        }
    };


    /**************************************************
     * CalendarGridAdapter.OnCalendarListener
     **************************************************/
    CalendarGridAdapter.OnCalendarListener onCalendarListener = new CalendarGridAdapter.OnCalendarListener() {
        @Override
        public void onClick(CalendarData data) {
            if (data.isEnable()) {
                mSelectDate = HFDateUtil.getDateFormat(mCurrentYear, data.getMonth(), data.getDay(), HFDateUtil.FORMAT_TASK_ADD_DUEDATE_SERVER);
                initData();
            } else {
                HFToastView toastView = new HFToastView(getContext());
                toastView.showToast(getContext().getString(R.string.calendar_alert), R.mipmap.ic_tp01, HFToastView.LENGTH_SHORT);
            }
        }
    };

    /**************************************************
     * Callback
     **************************************************/
    public interface OnDialogCallback {
        void onConfirm(@NonNull String selectedDate);
    }
}