/*
 * Copyright (c) 2015. Ncomz. All Rights Reserved
 */

package com.ntels.kneet.v3.view.dialog;

import android.app.Dialog;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.R;

import java.text.DecimalFormat;
import java.util.Calendar;

public class Dialog_Date extends Dialog implements View.OnClickListener {

    private Util   util     = new Util();
    private String sDate    = "";
    private String sMinDate = "";
    private String sMaxDate = "";
    private String sTitle   = "";
    private String sBtn1    = "";
    private String sBtn2    = "";
    private String sYear    = "";
    private String sMon     = "";
    private String sDay     = "";
    Button btnUpYear, btnDownYear;
    Button btnUpMon, btnDownMon;
    Button btnUpDay, btnDownDay;
    TextView tvUpYear, tvUpMon, tvUpDay;
    TextView tvDownYear, tvDownMon, tvDownDay;
    EditText edtYear, edtMon, edtDay;

    int iMinYear = 2015;
    int iMinMon  = 1;
    int iMinDay  = 1;

    int iMaxYear = 2035;
    int iMaxMon  = 12;
    int iMaxDay  = 31;

    int iMonStart = 1;
    int iMonEnd   = 12;
    int iDayStart = 1;
    int iDayEnd   = 31;

    private DecimalFormat decimalFormatYear = new DecimalFormat("0000");
    private DecimalFormat decimalFormat     = new DecimalFormat("00");
    final   String        DATE_FORMAT       = "%04d" + "-" + "%02d" + "-" + "%02d" + "";
    private Context ctx;

    private int BeforYear = 10;
    DatePickerListner dtp;
    TextView          tvTitle;
    TextView          tvBtn1;
    TextView          tvBtn2;
    LinearLayout      llBtn1;
    LinearLayout      llBtn2;
    public void init() {

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.dialog_date, null);
        this.setContentView(layout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        llBtn1 = (LinearLayout) findViewById(R.id.llBtn1);
        tvBtn1 = (TextView) findViewById(R.id.tvBtn1);
        llBtn2 = (LinearLayout) findViewById(R.id.llBtn2);
        tvBtn2 = (TextView) findViewById(R.id.tvBtn2);

        if ( "".equals(sTitle) ) {
            sTitle = util.getString(ctx, R.string.layout_date_selected);
        }
        if ( "".equals(sBtn1) ) {
            sBtn1 = util.getString(ctx, R.string.layout_selected);
        }
        if ( "".equals(sBtn2) ) {
            sBtn2 = util.getString(ctx, R.string.layout_cancel);
        }
        tvTitle.setText(sTitle);
        tvBtn1.setText(sBtn1);
        tvBtn2.setText(sBtn2);

        if ( "".equals(sMinDate) ) {
            iMinYear = util.null2int(util.getRealTimeType("yyyy"));
            iMinMon = 1;
            iMinDay = 1;
        } else {
            iMinYear = util.null2int(util.formattedDate(sMinDate, "yyyy-MM-dd", "yyyy"));
            iMinMon = util.null2int(util.formattedDate(sMinDate, "yyyy-MM-dd", "MM"));
            iMinDay = util.null2int(util.formattedDate(sMinDate, "yyyy-MM-dd", "dd"));
        }

        if ( "".equals(sMaxDate) ) {
            iMaxYear = iMinYear + 20;
            iMaxMon = 12;
            iMaxDay = 31;
        } else {
            iMaxYear = util.null2int(util.formattedDate(sMaxDate, "yyyy-MM-dd", "yyyy"));
            iMaxMon = util.null2int(util.formattedDate(sMaxDate, "yyyy-MM-dd", "MM"));
            iMaxDay = util.null2int(util.formattedDate(sMaxDate, "yyyy-MM-dd", "dd"));
        }

        Dlog.v("util.getDiffDate1(sMinDate, sMaxDate) = " + util.getDiffDate1(sMinDate, sMaxDate));
        Dlog.v("util.getDiffDate1(sMaxDate, sMinDate) = " + util.getDiffDate1(sMaxDate, sMinDate));
        Dlog.v("util.getDiffDate1(sMaxDate, sMinDate) = " + util.getDiffDate1(sMaxDate, sMinDate));

        if ( sDate.equals("") ) {
            if ( util.getDiffDate1(sMinDate, util.getRealTimeType("yyyy-MM-dd")) <= 0 ) {
                if ( util.getDiffDate1(sMaxDate, util.getRealTimeType("yyyy-MM-dd")) <= 0 ) {
                    sDate = sMaxDate;
                } else {
                    sDate = util.getRealTimeType("yyyy-MM-dd");
                }
            } else {
                sDate = sMinDate;
            }
        }

        sYear = util.formattedDate(sDate, "yyyy-MM-dd", "yyyy");
        sMon = util.formattedDate(sDate, "yyyy-MM-dd", "MM");
        sDay = util.formattedDate(sDate, "yyyy-MM-dd", "dd");

        displayListView();
    }

    public Dialog_Date(Context context) {

        super(context, R.style.NTLES_Dialog1);
        ctx = context;
    }

    public Dialog_Date(Context context, DatePickerListner dtpVal) {

        super(context, R.style.NTLES_Dialog1);
        ctx = context;
        dtp = dtpVal;
    }

    public Dialog_Date(Context context, String sTitleVal, String sDateVal, DatePickerListner dtpVal) {

        super(context, R.style.NTLES_Dialog1);
        ctx = context;
        sTitle = sTitleVal;
        sDate = sDateVal;
        dtp = dtpVal;
    }

    public Dialog_Date(Context context, String sTitleVal, String sBtn1Val, String sBtn2Val, String sDateVal, DatePickerListner dtpVal) {

        super(context, R.style.NTLES_Dialog1);
        ctx = context;
        sTitle = sTitleVal;
        sBtn1 = sBtn1Val;
        sBtn2 = sBtn2Val;
        sDate = sDateVal;
        dtp = dtpVal;
    }

    public void setTitle(String sTitleVal) {

        sTitle = sTitleVal;
    }

    public void setBtn1Val(String sBtn1Val) {

        sBtn1 = sBtn1Val;
    }

    public void setBtn2Val(String sBtn2Val) {

        sBtn2 = sBtn2Val;
    }

    public void setDateVal(String sDateVal) {

        sDate = sDateVal;
    }

    public void setMinDateVal(String sMinDateVal) {

        sMinDate = sMinDateVal;
    }

    public void setMaxDateVal(String sMaxDateVal) {

        sMaxDate = sMaxDateVal;
    }

    public void setDtpVal(DatePickerListner dtpVal) {

        dtp = dtpVal;
    }

    private void displayListView() {

        btnUpYear = (Button) findViewById(R.id.btnUpYear);
        btnUpMon = (Button) findViewById(R.id.btnUpMon);
        btnUpDay = (Button) findViewById(R.id.btnUpDay);
        btnDownYear = (Button) findViewById(R.id.btnDownYear);
        btnDownMon = (Button) findViewById(R.id.btnDownMon);
        btnDownDay = (Button) findViewById(R.id.btnDownDay);

        tvUpYear = (TextView) findViewById(R.id.tvUpYear);
        tvUpMon = (TextView) findViewById(R.id.tvUpMon);
        tvUpDay = (TextView) findViewById(R.id.tvUpDay);
        edtYear = (EditText) findViewById(R.id.edtYear);
        edtMon = (EditText) findViewById(R.id.edtMon);
        edtDay = (EditText) findViewById(R.id.edtDay);
        tvDownYear = (TextView) findViewById(R.id.tvDownYear);
        tvDownMon = (TextView) findViewById(R.id.tvDownMon);
        tvDownDay = (TextView) findViewById(R.id.tvDownDay);

        btnUpYear.setOnClickListener(this);
        tvUpYear.setOnClickListener(this);
        tvDownYear.setOnClickListener(this);
        btnDownYear.setOnClickListener(this);

        btnUpMon.setOnClickListener(this);
        tvUpMon.setOnClickListener(this);
        tvDownMon.setOnClickListener(this);
        btnDownMon.setOnClickListener(this);

        btnUpDay.setOnClickListener(this);
        tvUpDay.setOnClickListener(this);
        tvDownDay.setOnClickListener(this);
        btnDownDay.setOnClickListener(this);

        setKeyDisp();
        edtYear.setText(sYear);
        edtMon.setText(sMon);
        edtDay.setText(sDay);
        btnUpDay.performClick();
        btnDownDay.performClick();

        //        util.setKeyboardHide(act, util.getLinearLayout(act, R.id.llSvbody));
        llBtn1.setOnClickListener(this);
        llBtn2.setOnClickListener(this);
    }

    void setKeyDisp() {

        edtYear.setImeOptions(EditorInfo.IME_ACTION_DONE); // 키보드 확인 버튼 클릭시
        edtYear.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if ( actionId == EditorInfo.IME_ACTION_DONE ) {
                    edtYear.clearFocus();
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                return false;
            }
        });
        edtYear.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {

                if ( !hasFocus ) {
                    if ( edtYear.getText().toString().length() < 4 ) {
                        edtYear.setText(iMinYear + "");
                    }
                }
            }
        });

        //        int iMinYear = 2015;
        //        int iMaxYear   = 2035;
        //        int iMonStart = 1;
        //        int iMonEnd   = 12;
        //        int iDayStart = 1;
        //        int iDayEnd   = 31;
        edtYear.addTextChangedListener(new TextWatcher() {

            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override public void afterTextChanged(Editable s) {

                if ( util.null2int(s.toString()) > iMaxYear ) {
                    edtYear.setText(iMaxYear + "");
                    tvUpYear.setText(decimalFormatYear.format(iMaxYear - 1));
                    tvDownYear.setText(decimalFormatYear.format(iMinYear));
                    updateDays();
                } else if ( util.null2string(s.toString()).equals("") ) {
                    edtYear.setText(iMinYear + "");
                    tvUpYear.setText(decimalFormatYear.format(iMaxYear));
                    tvDownYear.setText(decimalFormatYear.format(iMinYear + 1));
                    updateDays();
                } else if ( s.toString().length() >= 4 ) {
                    int iCurentYear = util.null2int(s.toString());
                    if ( iCurentYear <= iMaxYear && iCurentYear >= iMinYear ) {
                        if ( iCurentYear == iMinYear ) {
                            tvUpYear.setText(decimalFormatYear.format(iMaxYear));
                        } else {
                            tvUpYear.setText(decimalFormatYear.format(iCurentYear - 1));
                        }
                        if ( iCurentYear < iMaxYear ) {
                            tvDownYear.setText(decimalFormatYear.format(iCurentYear + 1));
                        } else {
                            tvDownYear.setText(decimalFormatYear.format(iMinYear));
                        }
                    } else {
                        iCurentYear = iMinYear;
                        edtYear.setText(iMinYear + "");
                        tvUpYear.setText(decimalFormatYear.format(iMaxYear));
                        tvDownYear.setText(decimalFormatYear.format(iCurentYear + 1));
                    }
                    updateDays();
                    edtYear.selectAll();
                }
            }
        });
        edtMon.setImeOptions(EditorInfo.IME_ACTION_DONE); // 키보드 확인 버튼 클릭시
        edtMon.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if ( actionId == EditorInfo.IME_ACTION_DONE ) {
                    edtMon.clearFocus();
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                return false;
            }
        });
        edtMon.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {

                if ( !hasFocus ) {
                    if ( edtMon.getText().toString().length() == 1 ) {
                        edtMon.setText("0" + edtMon.getText());
                    }
                }
            }
        });
        edtMon.addTextChangedListener(new TextWatcher() {

            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override public void afterTextChanged(Editable s) {

                if ( util.null2int(s.toString()) > 12 ) {
                    edtMon.setText("12");
                } else if ( util.null2string(s.toString()).equals("") ) {
                    edtMon.setText("12");
                } else if ( s.toString().length() > 1 ) {
                    if ( util.null2int(s.toString()) == 0 ) {
                        edtMon.setText("01");
                    } else {
                        int iCurentMon = util.null2int(s.toString());
                        if ( iCurentMon <= iMonEnd ) {
                            if ( iCurentMon == iMonStart ) {
                                tvUpMon.setText(decimalFormat.format(iMonEnd));
                            } else {
                                tvUpMon.setText(decimalFormat.format(iCurentMon - 1));
                            }
                            if ( iCurentMon < iMonEnd ) {
                                tvDownMon.setText(decimalFormat.format(iCurentMon + 1));
                            } else {
                                tvDownMon.setText(decimalFormat.format(iMonStart));
                            }
                        } else {
                            iCurentMon = iMonStart;
                            tvUpMon.setText(decimalFormat.format(iMonEnd));
                            tvDownMon.setText(decimalFormat.format(iCurentMon + 1));
                        }
                        updateDays();
                        edtMon.selectAll();
                    }
                } else {
                    if ( util.null2int(s.toString()) > 1 ) {
                        edtMon.setText("0" + s.toString());
                    } else if ( util.null2int(s.toString()) > 0 ) {
                        int iCurentMon = util.null2int(s.toString());
                        if ( iCurentMon <= iMonEnd ) {
                            if ( iCurentMon == iMonStart ) {
                                tvUpMon.setText(decimalFormat.format(iMonEnd));
                            } else {
                                tvUpMon.setText(decimalFormat.format(iCurentMon - 1));
                            }
                            if ( iCurentMon < iMonEnd ) {
                                tvDownMon.setText(decimalFormat.format(iCurentMon + 1));
                            } else {
                                tvDownMon.setText(decimalFormat.format(iMonStart));
                            }
                        } else {
                            iCurentMon = iMonStart;
                            tvUpMon.setText(decimalFormat.format(iMonEnd));
                            tvDownMon.setText(decimalFormat.format(iCurentMon + 1));
                        }
                        updateDays();
                    }
                }
            }
        });

        edtDay.setImeOptions(EditorInfo.IME_ACTION_DONE); // 키보드 확인 버튼 클릭시
        edtDay.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if ( actionId == EditorInfo.IME_ACTION_DONE ) {
                    edtDay.clearFocus();
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                return false;
            }
        });
        edtDay.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {

                if ( !hasFocus ) {
                    if ( edtDay.getText().toString().length() == 1 ) {
                        edtDay.setText("0" + edtDay.getText());
                    }
                }
            }
        });
        edtDay.addTextChangedListener(new TextWatcher() {

            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override public void afterTextChanged(Editable s) {

                if ( util.null2int(s.toString()) > iDayEnd ) {
                    edtDay.setText(iDayEnd + "");
                } else if ( util.null2string(s.toString()).equals("") ) {
                    edtDay.setText("01");
                } else if ( s.toString().length() > 1 ) {
                    if ( util.null2int(s.toString()) == 0 ) {
                        edtDay.setText("01");
                    } else {
                        int iCurentDay = util.null2int(s.toString());
                        if ( iCurentDay <= iDayEnd ) {
                            if ( iCurentDay == iDayStart ) {
                                tvUpDay.setText(decimalFormat.format(iDayEnd));
                            } else {
                                tvUpDay.setText(decimalFormat.format(iCurentDay - 1));
                            }
                            if ( iCurentDay < iDayEnd ) {
                                tvDownDay.setText(decimalFormat.format(iCurentDay + 1));
                            } else {
                                tvDownDay.setText(decimalFormat.format(iDayStart));
                            }
                        } else {
                            iCurentDay = iDayStart;
                            tvUpDay.setText(decimalFormat.format(iDayEnd));
                            tvDownDay.setText(decimalFormat.format(iCurentDay + 1));
                        }
                        edtDay.selectAll();
                    }
                } else {
                    if ( util.null2int(s.toString()) > 1 ) {
                        edtDay.setText("0" + s.toString());
                    } else if ( util.null2int(s.toString()) > 0 ) {
                        int iCurentDay = util.null2int(s.toString());
                        if ( iCurentDay <= iDayEnd ) {
                            if ( iCurentDay == iDayStart ) {
                                tvUpDay.setText(decimalFormat.format(iDayEnd));
                            } else {
                                tvUpDay.setText(decimalFormat.format(iCurentDay - 1));
                            }
                            if ( iCurentDay < iDayEnd ) {
                                tvDownDay.setText(decimalFormat.format(iCurentDay + 1));
                            } else {
                                tvDownDay.setText(decimalFormat.format(iDayStart));
                            }
                        } else {
                            iCurentDay = iDayStart;
                            tvUpDay.setText(decimalFormat.format(iDayEnd));
                            tvDownDay.setText(decimalFormat.format(iCurentDay + 1));
                        }
                    }
                }
            }
        });
    }

    @Override public void onClick(View v) {

        int iCurentYear = util.null2int(edtYear.getText());
        int iCurentMon = util.null2int(edtMon.getText());
        int iCurentDay = util.null2int(edtDay.getText());
        switch (v.getId()) {
            case R.id.llBtn1:
                sDate = decimalFormatYear.format(iCurentYear) + "-" + decimalFormat.format(iCurentMon) + "-" + decimalFormat.format(iCurentDay);
                dtp.OnDoneButton(Dialog_Date.this, sDate);
                break;
            case R.id.llBtn2:
                dtp.OnCancelButton(Dialog_Date.this);
                break;
            case R.id.btnUpYear:
            case R.id.tvUpYear:
                if ( iCurentYear > iMinYear ) {
                    iCurentYear--;
                    edtYear.setText(decimalFormatYear.format(iCurentYear));
                } else {
                    iCurentYear = iMaxYear;
                    edtYear.setText(decimalFormatYear.format(iCurentYear));
                }

                break;
            case R.id.tvDownYear:
            case R.id.btnDownYear:
                if ( iCurentYear < iMaxYear ) {
                    iCurentYear++;
                    edtYear.setText(decimalFormatYear.format(iCurentYear));
                } else {
                    iCurentYear = iMinYear;
                    edtYear.setText(decimalFormatYear.format(iCurentYear));
                }
                break;
            case R.id.btnUpMon:
            case R.id.tvUpMon:
                if ( iCurentMon > iMonStart ) {
                    iCurentMon--;
                    edtMon.setText(decimalFormat.format(iCurentMon));
                } else {
                    iCurentMon = iMonEnd;
                    edtMon.setText(decimalFormat.format(iCurentMon));
                }
                break;
            case R.id.tvDownMon:
            case R.id.btnDownMon:
                if ( iCurentMon < iMonEnd ) {
                    iCurentMon++;
                    edtMon.setText(decimalFormat.format(iCurentMon));
                } else {
                    iCurentMon = iMonStart;
                    edtMon.setText(decimalFormat.format(iCurentMon));
                }
                break;
            case R.id.btnUpDay:
            case R.id.tvUpDay:
                if ( iCurentDay > iDayStart ) {
                    iCurentDay--;
                    edtDay.setText(decimalFormat.format(iCurentDay));
                } else {
                    iCurentDay = iDayEnd;
                    edtDay.setText(decimalFormat.format(iCurentDay));
                }
                break;
            case R.id.tvDownDay:
            case R.id.btnDownDay:
                if ( iCurentDay < iDayEnd ) {
                    iCurentDay++;
                    edtDay.setText(decimalFormat.format(iCurentDay));
                } else {
                    iCurentDay = iDayStart;
                    edtDay.setText(decimalFormat.format(iCurentDay));
                }
                break;
            default:
                break;
        }
    }

    private void updateDays() {

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, util.null2int(edtYear.getText()));
        calendar.set(Calendar.MONTH, util.null2int(edtMon.getText()) - 1);

        int maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

        iDayEnd = maxDays;
        int curDay = Math.min(maxDays, util.null2int(edtDay.getText().toString()));
        edtDay.setText(curDay + "");
    }

    public interface DatePickerListner {

        public void OnDoneButton(Dialog dialogVal, String sDateVal);

        public void OnCancelButton(Dialog dialogVal);
    }
}
