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

package com.ntels.onecable.view;

import com.ntels.onecable.R;
import com.ntels.onecable.common.AppConfig;
import com.ntels.onecable.common.Constants;
import com.ntels.onecable.common.c_interface.OnDataSendToReslut;
import com.ntels.onecable.common.http.HttpSend;
import com.ntels.onecable.common.http.Response;
import com.ntels.onecable.common.util.Dlog;
import com.ntels.onecable.common.util.Util;
import com.ntels.onecable.common.widget.CustomActivity;
import com.ntels.onecable.view.dialog.CustomDialog;
import com.ntels.onecable.view.dialog.DialogSpinner;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * <pre>
 * 1. ClassName :   FindPassword2nd
 * 2. FileName  :   FindPassword2nd.java
 * 3. Package   :   com.ntels.onecable.view
 * 4. Date      :   2016-11-28
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class FindPassword2nd extends CustomActivity implements View.OnClickListener,
        CustomDialog.OnMsgAlterToResult {

    private static final int MSG_COM_G_HOMEGRP_MEMBERS_QUIZ_LIST = 1;
    private static final int MSG_COM_P_MEMBER_PASSWORD = 2;

    private static final String FIND_PASSWORD_CURRENT_STEP = "2";

    private Activity mActivity;
    private Intent mIntent;
    private AppConfig mAppConfig;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private int mType = 0;
    private ArrayList<HashMap<String, Object>> mQuizData = new ArrayList<HashMap<String, Object>>();
    private ArrayList<String> mQuizNameList = new ArrayList<>();
    private int mQuizPosition = -1;
    private HashMap<String, Object> mSelectedQuiz = new HashMap<>();
    private String mLoginId = "";
    private String mCellphone = "";
    private String mSelectedQuizId = "";
    private String mAnswer = "";

    @BindView(R.id.rlQuestion) RelativeLayout mQuestion;
    @BindView(R.id.tvQuestion) TextView mQuestionText;
    @BindView(R.id.edtYear) EditText mYear;
    @BindView(R.id.edtMonth) EditText mMonth;
    @BindView(R.id.edtDay) EditText mDay;
    @BindView(R.id.llBtn1) LinearLayout mOk;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mActivity = FindPassword2nd.this;
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);

        View viewToLoad = LayoutInflater.from(mActivity).inflate(R.layout.find_password_2nd, null);
        this.setContentView(viewToLoad);

        ButterKnife.bind(this);

        if (null != getIntent()) {
            mLoginId = getIntent().getStringExtra(Constants.EXTRA_MEMBER_ID);
            mCellphone = getIntent().getStringExtra(Constants.EXTRA_PHONE);
        }

        setToolbar();
        displayListView();
        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_HOMEGRP_MEMBERS_QUIZ_LIST), Constants.HANDLER_DELAY_MILLIS);
    }

    @Override
    public void onBackPressed() {

        mIntent = new Intent();
        mActivity.setResult(RESULT_CANCELED, mIntent);
        finish();
        return;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_FIND_PASSWORD_3RD:
                    mIntent = new Intent();
                    setResult(RESULT_OK, mIntent);
                    finish();
                    break;
                case Constants.ACT_SPINNER:
                    mQuizPosition = data.getIntExtra(Constants.EXTRA_SPINNER_RESULT, -1);
                    mSelectedQuiz = mQuizData.get(mQuizPosition);
                    mQuestionText.setText(mUtil.null2string(mSelectedQuiz.get(Constants.KEY_QUIZ)));
                    checkFormValid();
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_SPINNER:
                    break;
                default:
                    onBackPressed();
                    break;
            }
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    @OnClick({R.id.rlQuestion, R.id.llBtn1, R.id.llBtn2})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.rlQuestion:
                showQuizSpinner();
                break;
            case R.id.llBtn1:
                mSelectedQuizId = mUtil.null2string(mSelectedQuiz.get(Constants.KEY_QUIZ_ID));
                mAnswer = mYear.getText().toString() + mMonth.getText().toString() + mDay.getText().toString();
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_MEMBER_PASSWORD), Constants.HANDLER_DELAY_MILLIS);
                /*mIntent = new Intent(mActivity, FindPassword3rd.class);
                mIntent.putExtra(Constants.EXTRA_MEMBER_ID, mLoginId);
                mIntent.putExtra(Constants.EXTRA_PHONE, mCellphone);
                mIntent.putExtra(Constants.EXTRA_QUIZ_ID, mUtil.null2string(mSelectedQuiz.get(Constants.KEY_QUIZ_ID)));
                mIntent.putExtra(Constants.EXTRA_QUIZ_ANSWER, answerDate);
                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_FIND_PASSWORD_2ND);*/
                break;
            case R.id.llBtn2:
                onBackPressed();
                break;
            default:
                break;
        }
    }

    @Override
    public void resultCustomDialogResponse(int msgId, int btnResult) {

        switch (msgId) {

            case Constants.MSG807:
                if (btnResult == 1) {
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(mType),
                            Constants.HANDLER_DELAY_MILLIS);
                } else {
                    mActivity.finish();
                }
                break;
            case Constants.MSG840:
                mActivity.finish();
                break;
            default:
                break;
        }
    }

    Handler mComHandler = new Handler(new IncomingHandlerCallBack());

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_G_HOMEGRP_MEMBERS_QUIZ_LIST:
                    sendGetHomegrpMembersQuizList();
                    break;
                case MSG_COM_P_MEMBER_PASSWORD:
                    sendPostMemberPassword();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

    /**
     * 툴바 셋팅.
     */
    private void setToolbar() {

        Toolbar toolbar = (Toolbar) mActivity.findViewById(R.id.toolbar);
        mUtil.setKeyboardHide(mActivity, toolbar);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle1).setVisibility(View.VISIBLE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle2).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitleDivider).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle3).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle4).setVisibility(View.GONE);
        mUtil.getView(toolbar, R.id.llJoinStep).setVisibility(View.VISIBLE);
        mUtil.getTextView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.btnToolbarMore).setVisibility(View.GONE);

        mUtil.getTextView(toolbar, R.id.tvToolbarTitle1).setText(mUtil.getString(mActivity, R.string.layout_find_password_2nd_01));
        mUtil.getTextView(toolbar, R.id.tvCurrentStep).setText(FIND_PASSWORD_CURRENT_STEP);
        mUtil.getTextView(toolbar, R.id.tvTotalStep).setText(Constants.FIND_PASSWORD_TOTAL_STEP);
    }

    /**
     * UI display.
     */
    private void displayListView() {
        mOk.setEnabled(false);
        mYear.addTextChangedListener(mTextWatcher);
        mMonth.addTextChangedListener(mTextWatcher);
        mDay.addTextChangedListener(mTextWatcher);
    }

    private TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            checkFormValid();
        }
    };

    /**
     * 사용자 입력 필드 체크.
     *
     * @return 체크 결과
     */
    private void checkFormValid() {

        boolean isEnable = true;

        isEnable &= mQuestionText.length() > 0;
        isEnable &= mYear.length() == 4;
        isEnable &= mMonth.length() == 2;
        isEnable &= mDay.length() == 2;

        mOk.setEnabled(isEnable);
    }

    /**
     * [REST][GET] 인증 퀴즈 목록 요청.
     *
     */
    private void sendGetHomegrpMembersQuizList() {
        try {
            HttpSend httpSend;
            httpSend = new HttpSend(mActivity);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultGetHomegrpMemberQuizList(result);
                }
            });

            httpSend.getHomeGroupMembersQuizList();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 인증 퀴즈 목록 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultGetHomegrpMemberQuizList(Response result) {
        try {
            if (result.getStatusCode() == 200) {
                JSONObject joResult = new JSONObject(result.getContent());
                String quizList = mUtil.null2string(joResult.get(Constants.KEY_QUIZ_LIST));
                mQuizData = mUtil.jsonToArrayListMap(quizList);
                for (HashMap<String, Object> quiz : mQuizData) {
                    mQuizNameList.add(mUtil.null2string(quiz.get(Constants.KEY_QUIZ)));
                }
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * [REST][POST] 비밀번호 찾기 요청.
     *
     */
    private void sendPostMemberPassword() {
        try {
            HttpSend httpSend;
            httpSend = new HttpSend(mActivity);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultPostMemberPassword(result);
                }
            });

            httpSend.postMemberPassword(mLoginId, mCellphone, mSelectedQuizId, mAnswer);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 비밀번호 찾기 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultPostMemberPassword(Response result) {
        try {
            if (result.getStatusCode() == 200) {
                JSONObject joResult = new JSONObject(result.getContent());
                mIntent = new Intent(mActivity, FindPassword3rd.class);
                mIntent.putExtra(Constants.EXTRA_NICKNAME, mUtil.null2string(joResult.get(Constants.KEY_NICKNAME)));
                mIntent.putExtra(Constants.EXTRA_MEMBER_ID, mLoginId);
                mIntent.putExtra(Constants.EXTRA_QUIZ_ID, mSelectedQuizId);
                mIntent.putExtra(Constants.EXTRA_PHONE, mCellphone);
                mIntent.putExtra(Constants.EXTRA_QUIZ_ANSWER, mAnswer);
                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_FIND_PASSWORD_3RD);
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    private void showQuizSpinner() {
        Intent intent = new Intent();
        intent.setClass(mActivity, DialogSpinner.class);
        intent.putExtra(Constants.EXTRA_SPINNER_LIST1, mQuizNameList);
        intent.putExtra(Constants.EXTRA_SPINNER_TITLE, mUtil.getString(mActivity, R.string.layout_find_password_2nd_03));
        intent.putExtra(Constants.EXTRA_SPINNER_TYPE, 0);
        intent.putExtra(Constants.EXTRA_SPINNER_SHOW_TYPE, 1);
//        intent.putExtra(Constants.EXTRA_SPINNER_POSITION, mDevicePosition);
        mUtil.callActivityForResult(mActivity, intent, Constants.ACT_SPINNER, Constants.CHANGE_EVENT_BOTTOM_BOTTOM);
    }

}
