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

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

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

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

/**
 * <pre>
 * 1. ClassName :   SettingCellphoneChange
 * 2. FileName  :   SettingCellphoneChange.java
 * 3. Package   :   com.ntels.onecable.admin.view.mainmore
 * 4. Date      :   2017-04-24
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class SettingCellphoneChange extends CustomActivity implements CustomDialog.OnMsgAlterToResult {

    private static final int MSG_COM_P_SEND_PIN = 1;
    private static final int MSG_COM_P_CHANGE_CELLPHONE = 2;

    private static final String AUTH_TYPE_CHANGE_CELLPHONE = "1";

    private static final String ERROR_CODE_WAITING_TIME = "120";

    /*통신 관련*/
    private int type = 0;

    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Intent mIntent;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();

    @BindView(R.id.edtCellphone)
    EditText mCellphone;
    @BindView(R.id.edtPin)
    EditText mPin;
    @BindView(R.id.llBtn1)
    LinearLayout mOk;
    @BindView(R.id.btnSendPin)
    Button mSendPin;
    @BindView(R.id.tvInfoMsg)
    TextView mInfoMsg;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

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

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

        ButterKnife.bind(this);

        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.getTextView(toolbar, R.id.tvToolbarTitle1)
                .setText(mUtil.getString(mActivity, R.string.layout_setting_cellphone_change_01));
    }

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

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

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

        switch (view.getId()) {
            case R.id.llBtn1:
                mOk.setEnabled(false);
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_CHANGE_CELLPHONE), Constants.HANDLER_DELAY_MILLIS);
                break;
            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;
        }
    }

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

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            type = msg.what;
            switch (msg.what) {
                case MSG_COM_P_SEND_PIN:
                    sendPostSendPin();
                    break;
                case MSG_COM_P_CHANGE_CELLPHONE:
                    sendPutChangeCellphone();
                    break;
                default:
                    break;
            }
            return true;
        }
    }

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

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

                    resultPostSendPin(result);
                }
            });

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

    /**
     * {@link #sendPostSendPin()} 요청 결과.
     */
    private void resultPostSendPin(Response response) {
        try {
            if (response.getStatusCode() == 200) {
                mSendPin.setText(getString(R.string.layout_setting_cellphone_change_07));
                mInfoMsg.setText(getString(R.string.layout_setting_cellphone_change_05));
            } 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)) {
                    mInfoMsg.setText(errorMsg);
                } else {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, errorMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * 휴대폰 변호 변경 요청.
     */
    private void sendPutChangeCellphone() {

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

                    resultPutChangeCellphone(result);
                }
            });

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

    /**
     * {@link #sendPutChangeCellphone()} 요청 결과.
     */
    private void resultPutChangeCellphone(Response response) {
        try {
            if (response.getStatusCode() == 200) {
                mUtil.setShowToast(mActivity, getString(R.string.MSG928), Toast.LENGTH_SHORT);
                mIntent = new Intent();
                mActivity.setResult(RESULT_OK, mIntent);
                finish();
            } 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)) {
                    mInfoMsg.setText(errorMsg);
                } else {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, errorMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }

        try {
            mOk.setEnabled(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

 /* *//**
     * 회원 정보 수정(닉네임 정보에 대해 변경 처리한다) 요청.
     *//*
  private void sendPutMemberInfo() {

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

          resultPutMemberInfo(result);
        }
      });

      //공통 변수 입력
      httpSend.putChangeMemberInfo(Constants.KEY_NICKNAME, mNickname.getText().toString());
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  */

    /**
     * {@link #sendPutMemberInfo()} 요청 결과.
     *
     * @param response 결과 data
     *//*
  private void resultPutMemberInfo(Response response) {

    try {
      if (response.getStatusCode() == 200) {

//        mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG843), Toast.LENGTH_SHORT);
        mIntent = new Intent();
        mActivity.setResult(RESULT_OK, mIntent);
        finish();
      } 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);
    }
    try {
      mOk.setEnabled(true);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }*/
    @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(type), Constants.HANDLER_DELAY_MILLIS);
                }
                break;
            default:
                break;
        }
    }
}
