package com.ntels.onecable.view.join;

import com.ntels.onecable.R;
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 org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
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.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.HashMap;

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

/**
 * <pre>
 * 1. ClassName :   JoinStep4th
 * 2. FileName  :   JoinStep4th.java
 * 3. Package   :   com.ntels.onecable.view.join
 * 4. Date      :   2017-04-26
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */

public class JoinStep4th extends CustomActivity implements CustomDialog.OnMsgAlterToResult {

    private static final String JOIN_CURRENT_STEP = "4";

    private static final int MSG_COM_G_SEND_MEMBER_EXIST = 1;
    private static final int MSG_COM_P_SEND_JOIN_MASTER = 2;
    private static final int MSG_COM_P_SEND_JOIN_MEMBER = 3;

    private Activity mActivity;
    private CustomDialog mCustomDialog = new CustomDialog();
    private Util mUtil = new Util();
    private int mType;
    private Intent mIntent;
    private boolean mIsIdCheck = false;
    private HashMap<String, Object> mSelectedQuiz;
    private String mGradeCode = "";
    private String mPhone = "";
    private String mQuizAnswer = "";
    private String mCustId = "";
    private String mCtrtGrpId = "";

    @BindView(R.id.edtId) EditText mId;
    @BindView(R.id.edtPw) EditText mPw;
    @BindView(R.id.edtPwConfirm) EditText mPwConfirm;
    @BindView(R.id.btnCheckId) Button mCheckId;
    @BindView(R.id.llBtn1) LinearLayout mNext;
    @BindView(R.id.tvCheckResult) TextView mCheckResult;

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

        mActivity = JoinStep4th.this;
        mCustomDialog.setOnMsgAlterToResultEvent(this);

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

        ButterKnife.bind(this);

        if (null != getIntent()) {
            mGradeCode = getIntent().getStringExtra(Constants.EXTRA_GRADE_CODE);
            mPhone = getIntent().getStringExtra(Constants.EXTRA_PHONE);
            mCustId = getIntent().getStringExtra(Constants.EXTRA_CUST_ID);
            mCtrtGrpId = getIntent().getStringExtra(Constants.EXTRA_CTRT_GRP_ID);
            if (Constants.GRADE_CODE_MAS.equals(mGradeCode)) {
                mSelectedQuiz = (HashMap<String, Object>) getIntent().getSerializableExtra(Constants.EXTRA_SELECTED_QUIZ);
                mQuizAnswer = getIntent().getStringExtra(Constants.EXTRA_QUIZ_ANSWER);
            }
        }

        setToolbar();
        displayView();
    }

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

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_JOIN_STEP_5TH:
                    mIntent = new Intent();
                    setResult(RESULT_OK, mIntent);
                    finish();
                    break;
                default:
                    break;
            }
        } else {
            onBackPressed();
        }
    }

    private void checkValidForm() {

        boolean isEnable = true;

        isEnable &= mIsIdCheck;
        isEnable &= mPw.length() >= 8;
        isEnable &= mPwConfirm.length() >= 8;

        mNext.setEnabled(isEnable);
    }

    private void displayView() {
        mCheckId.setEnabled(false);
        mNext.setEnabled(false);
        mPw.setEnabled(false);
        mPwConfirm.setEnabled(false);
        mId.addTextChangedListener(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) {
                if (editable.length() >= 6) {
                    mCheckId.setEnabled(true);
                } else {
                    mCheckId.setEnabled(false);
                }
            }
        });
        mPw.addTextChangedListener(mPwTextWatcher);
        mPwConfirm.addTextChangedListener(mPwTextWatcher);
    }

    private TextWatcher mPwTextWatcher = 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) {
            checkValidForm();
        }
    };

    /**
     * 툴바 셋팅.
     */
    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.getTextView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
        mUtil.getView(toolbar, R.id.llJoinStep).setVisibility(View.VISIBLE);

        mUtil.getTextView(toolbar, R.id.tvCurrentStep).setText(JOIN_CURRENT_STEP);
        mUtil.getTextView(toolbar, R.id.tvTotalStep).setText(Constants.JOIN_TOTAL_STEP);

        mUtil.getTextView(toolbar, R.id.tvToolbarTitle1)
                .setText(mUtil.getString(mActivity, R.string.layout_join_step_4th_01));
    }

    @OnClick({R.id.btnCheckId, R.id.llBtn1, R.id.llBtn2})
    public void onClick(View view) {
       switch (view.getId()) {
           case R.id.btnCheckId:
               mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_SEND_MEMBER_EXIST), Constants.HANDLER_DELAY_MILLIS);
               break;
           case R.id.llBtn1:
               if (Constants.GRADE_CODE_MAS.equals(mGradeCode)) {
                   mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_SEND_JOIN_MASTER), Constants.HANDLER_DELAY_MILLIS);
               } else {
                   mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_SEND_JOIN_MEMBER), Constants.HANDLER_DELAY_MILLIS);
               }
               break;
           case R.id.llBtn2:
               onBackPressed();
               break;
           default:
               break;
       }
    }

    private Handler mComHandler = new Handler(new JoinStep4th.IncomingHandlerCallBack());

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_G_SEND_MEMBER_EXIST:
                    sendGetMemberIdExist();
                    break;
                case MSG_COM_P_SEND_JOIN_MASTER:
                    sendPostJoinMaster();
                    break;
                case MSG_COM_P_SEND_JOIN_MEMBER:
                    sendPostJoinMember();
                    break;
                default:
                    break;
            }
            return true;
        }
    }

    @Override
    public void onBackPressed() {

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

    @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);
                }
                break;
            case Constants.MSG000:
                mId.setText("");
                break;
            default:
                break;
        }
    }

    /**
     * 회원가입 할 ID 중복체크.
     */
    private void sendGetMemberIdExist() {

        try {
            HttpSend httpSend = new HttpSend(mActivity);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultGetMemberIdExist(result);
                }
            });

            //공통 변수 입력
            httpSend.getMemberIdExist(mCustId, mCtrtGrpId, mId.getText().toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * {@link #sendGetMemberIdExist()} 요청 결과.
     */
    private void resultGetMemberIdExist(Response response) {
        try {
            if (response.getStatusCode() == 200) {
                mIsIdCheck = true;
                mCheckResult.setVisibility(View.VISIBLE);
                mPw.setEnabled(true);
                mPwConfirm.setEnabled(true);
                checkValidForm();
//                mNext.setEnabled(true);
                return;
            } else {
                JSONObject joResult = new JSONObject(response.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);
        }
        mIsIdCheck = false;
        mCheckResult.setVisibility(View.GONE);
        mPw.setEnabled(false);
        mPwConfirm.setEnabled(false);
        mNext.setEnabled(false);
    }

    /**
     * 마스터회원 가입 요청.
     */
    private void sendPostJoinMaster() {

        try {
            HttpSend httpSend = new HttpSend(mActivity);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultPostJoinMaster(result);
                }
            });

            //공통 변수 입력
            httpSend.postJoinMaster(mId.getText().toString(), mPhone, mPw.getText().toString(),
                    mUtil.null2string(mSelectedQuiz.get(Constants.KEY_QUIZ_ID)), mUtil.null2string(mSelectedQuiz.get(Constants.KEY_QUIZ)),
                    mQuizAnswer, mUtil.null2string(mSelectedQuiz.get(Constants.KEY_STATUS_CODE)));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * {@link #sendPostJoinMaster()} 요청 결과.
     */
    private void resultPostJoinMaster(Response response) {
        try {
            if (response.getStatusCode() == 201) {

                mIntent = new Intent(mActivity, JoinStep5th.class);
                mIntent.putExtra(Constants.EXTRA_CUST_ID, mCustId);
                mIntent.putExtra(Constants.EXTRA_CTRT_GRP_ID, mCtrtGrpId);
                mIntent.putExtra(Constants.EXTRA_LOGIN_ID, mId.getText().toString());
                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_JOIN_STEP_5TH);
            } else {
                JSONObject joResult = new JSONObject(response.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);
        }
        mIsIdCheck = false;
        mCheckResult.setVisibility(View.GONE);
        mPw.setEnabled(false);
        mPwConfirm.setEnabled(false);
        mNext.setEnabled(false);
    }

    /**
     * 마스터회원 가입 요청.
     */
    private void sendPostJoinMember() {

        try {
            HttpSend httpSend = new HttpSend(mActivity);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultPostJoinMember(result);
                }
            });

            //공통 변수 입력
            httpSend.postJoinMember(mId.getText().toString(), mPhone, mPw.getText().toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * {@link #sendPostJoinMember()} 요청 결과.
     */
    private void resultPostJoinMember(Response response) {
        try {
            if (response.getStatusCode() == 201) {

                mIntent = new Intent(mActivity, JoinStep5th.class);
                mIntent.putExtra(Constants.EXTRA_CUST_ID, mCustId);
                mIntent.putExtra(Constants.EXTRA_CTRT_GRP_ID, mCtrtGrpId);
                mIntent.putExtra(Constants.EXTRA_LOGIN_ID, mId.getText().toString());
                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_JOIN_STEP_5TH);
            } else {
                JSONObject joResult = new JSONObject(response.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);
        }
        mIsIdCheck = false;
        mCheckResult.setVisibility(View.GONE);
        mPw.setEnabled(true);
        mPwConfirm.setEnabled(true);
        mNext.setEnabled(false);
    }
}
