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

package com.ntels.onecable.admin.view.customer;

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

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

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

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

    public static final String AUTH_TYPE_JOIN_MASTER = "3";
    private static final int MSG_COM_P_SEND_PIN = 1;
    private static final int MSG_COM_P_PHONE_RESPONSE = 2;
    private static final String SEND_TYPE_USER = "U";
    private static final String ERROR_CODE_WAITING_TIME = "120";

    private static final String JOIN_CURRENT_STEP = "2";
    @BindView(R.id.edtCellphone) EditText mCellphone;
    @BindView(R.id.btnSendPin) Button mSendPin;
    @BindView(R.id.tvSendPinMsg) TextView mSendPinMsg;
    Handler mComHandler = new Handler(new IncomingHandlerCallBack());
    /*통신 관련*/
    private int mType = 0;
    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Intent mIntent;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private String mCtrtGrpId = "";
    private String mCustId = "";


    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

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

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

        ButterKnife.bind(this);

        Intent intent = getIntent();
        mCustId = intent.getStringExtra(Constants.KEY_CUST_ID);
        mCtrtGrpId = intent.getStringExtra(Constants.KEY_CTRT_GRP_ID);

        setToolbar();
        setDisp();
    }

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


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

    /**
     * UI display.
     */
    private void setDisp() {
        mSendPin.setEnabled(false);
        mCellphone.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() >= 10) {
                    mSendPin.setEnabled(true);
                } else {
                    mSendPin.setEnabled(false);
                }
            }
        });
    }

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

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

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

        switch (view.getId()) {
            case R.id.llBtn2:
                onBackPressed();
                break;
            case R.id.btnSendPin:
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_SEND_PIN), Constants.HANDLER_DELAY_MILLIS);
                break;
            default:
                break;
        }
    }

    /**
     * 휴대폰 핀번호 발송 요청.
     */
    private void sendPostSendPin() {

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

                    resultPostSendPin(result);
                }
            });

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

    /**
     * {@link #sendPostSendPin()} 요청 결과.
     */
    private void resultPostSendPin(Response response) {
        try {
            if (response.getStatusCode() == 200) {
                mSendPin.setText(getString(R.string.layout_customer_join_master_04));
                mSendPinMsg.setText(getString(R.string.layout_customer_join_master_06));
            } 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));

                if (ERROR_CODE_WAITING_TIME.equals(errorCode)) {
                    mSendPinMsg.setText(errorMsg);
                } else {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, errorMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * 휴대폰번호 인증번호 확인.
     */
    private void sendPostPhoneResponse() {

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

                    resultPostPhoneResponse(result);
                }
            });

            //공통 변수 입력
//            httpSend.postConfirmPin(mCellphone.getText().toString(), mPin.getText().toString(), SEND_TYPE_USER, AUTH_TYPE_JOIN_MASTER);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * {@link #sendPostPhoneResponse()} 요청 결과.
     */
    private void resultPostPhoneResponse(Response response) {
        try {
            if (response.getStatusCode() == 200) {
//                JSONObject joResult = new JSONObject(response.getContent());
//                String custId = mUtil.null2string(joResult.get(Constants.KEY_CUST_ID));
//                String ctrtGrpId = mUtil.null2string(joResult.get(Constants.KEY_CTRT_GRP_ID));
//                mIntent = new Intent(mActivity, JoinStep3rdMember.class);
//                mIntent.putExtra(Constants.EXTRA_PHONE, mCellphone.getText().toString());
//                mIntent.putExtra(Constants.EXTRA_CUST_ID, custId);
//                mIntent.putExtra(Constants.EXTRA_CTRT_GRP_ID, ctrtGrpId);
//                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_JOIN_STEP_3RD_MEMBER);
            } 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);
        }
    }

    @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;
        }
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_P_SEND_PIN:
                    sendPostSendPin();
                    break;
                case MSG_COM_P_PHONE_RESPONSE:
                    sendPostPhoneResponse();
                    break;
                default:
                    break;
            }
            return true;
        }
    }

}
