package com.ntels.onecable.view.join;

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 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.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

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

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

public class JoinStep3rdMember extends CustomActivity implements CustomDialog.OnMsgAlterToResult {

    private static final String JOIN_CURRENT_STEP = "3";

    private static final int MSG_COM_P_QUIZ_REQUEST = 1;
    private static final int MSG_COM_P_QUIZ_RESPONSE = 2;

    private Activity mActivity;
    private CustomDialog mCustomDialog = new CustomDialog();
    private Util mUtil = new Util();
    private AppConfig mAppConfig;
    private int mType;
    private Intent mIntent;
    private String mCustId = "";
    private String mCtrtGrpId = "";
    private String mCellphone = "";

    @BindView(R.id.tvQuiz) TextView mQuiz;
    @BindView(R.id.edtYear) EditText mYear;
    @BindView(R.id.edtMonth) EditText mMonth;
    @BindView(R.id.edtDay) EditText mDay;
    @BindView(R.id.llBtn1) LinearLayout mNext;

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

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

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

        ButterKnife.bind(this);

        if (null != getIntent()) {
            mCustId = getIntent().getStringExtra(Constants.EXTRA_CUST_ID);
            mCtrtGrpId = getIntent().getStringExtra(Constants.EXTRA_CTRT_GRP_ID);
            mCellphone = getIntent().getStringExtra(Constants.EXTRA_PHONE);
        }

        setToolbar();
        displayView();
        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_QUIZ_REQUEST), Constants.HANDLER_DELAY_MILLIS);
    }

    private void displayView() {
        mNext.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) {
            checkValidForm();
        }
    };

    private void checkValidForm() {
        boolean isEnable = true;
        isEnable &= mYear.getText().length() == 4;
        isEnable &= mMonth.getText().length() == 2;
        isEnable &= mDay.getText().length() == 2;

        mNext.setEnabled(isEnable);
    }

    /**
     * 툴바 셋팅.
     */
    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_3rd_member_01));
    }

    @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_4TH:
                    mIntent = new Intent();
                    setResult(RESULT_OK, mIntent);
                    finish();
                    break;
                default:
                    break;
            }
        } else {
            onBackPressed();
        }
    }

    @OnClick({R.id.llBtn1, R.id.llBtn2})
    public void onClick(View view) {
       switch (view.getId()) {
           case R.id.llBtn1:
               mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_QUIZ_RESPONSE), Constants.HANDLER_DELAY_MILLIS);
//               mIntent = new Intent(mActivity, JoinStep4th.class);
//               mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_JOIN_STEP_4TH);
               break;
           case R.id.llBtn2:
               onBackPressed();
               break;
           default:
               break;
       }
    }

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

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_P_QUIZ_REQUEST:
                    sendPostQuizRequest();
                    break;
                case MSG_COM_P_QUIZ_RESPONSE:
                    sendPostQuizResponse();
                    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;
            default:
                break;
        }
    }

    /**
     * 마스터가 선택한 인증 퀴즈 요청.
     */
    private void sendPostQuizRequest() {

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

                    resultPostQuizRequest(result);
                }
            });

            //공통 변수 입력
            httpSend.postMemberQuizRequest(mCustId, mCtrtGrpId, mCellphone);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * {@link #sendPostQuizRequest()} 요청 결과.
     */
    private void resultPostQuizRequest(Response response) {
        try {
            if (response.getStatusCode() == 200) {
                JSONObject joResult = new JSONObject(response.getContent());
                mNext.setEnabled(true);
                mQuiz.setText(joResult.getString(Constants.KEY_QUIZ));
                return;
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                mCustomDialog.msgAlert(mActivity, Constants.MSG000, errorMsg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
        mNext.setEnabled(false);
    }

    /**
     * 마스터가 선택한 인증 퀴즈 정답 확인.
     */
    private void sendPostQuizResponse() {

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

                    resultPostQuizResponse(result);
                }
            });

            //공통 변수 입력
            httpSend.postMemberQuizRequest(mCustId, mCtrtGrpId, mCellphone);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * {@link #sendPostQuizResponse()} 요청 결과.
     */
    private void resultPostQuizResponse(Response response) {
        try {
            if (response.getStatusCode() == 200) {
                mNext.setEnabled(true);
                mIntent = new Intent(mActivity, JoinStep4th.class);
                mIntent.putExtra(Constants.EXTRA_PHONE, mCellphone);
                mIntent.putExtra(Constants.EXTRA_CUST_ID, mCustId);
                mIntent.putExtra(Constants.EXTRA_CTRT_GRP_ID, mCtrtGrpId);
                mIntent.putExtra(Constants.EXTRA_GRADE_CODE, Constants.GRADE_CODE_SIM);
                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_JOIN_STEP_4TH);
                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);
        }
        mNext.setEnabled(false);
    }
}
