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

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

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

    private static final int MSG_COM_P_MEMBER_PASSWORD_EXIST = 1;
    Handler mComHandler = new Handler(new IncomingHandlerCallBack());
    /*통신 관련*/
    private int mTag = 0;
    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Intent mIntent;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    @BindView(R.id.llBtn1) LinearLayout mOk;
    @BindView(R.id.edtPassword) EditText mPassword;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

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

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

        ButterKnife.bind(this);

        setToolbar();
        displayView();
    }

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

    private void displayView() {
        mOk.setEnabled(false);
        mPassword.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() >= 8) {
                    mOk.setEnabled(true);
                } else {
                    mOk.setEnabled(false);
                }
            }
        });
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

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

        switch (view.getId()) {
            case R.id.llBtn1:
                view.setEnabled(false);
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_MEMBER_PASSWORD_EXIST), Constants.HANDLER_DELAY_MILLIS);
                break;
            case R.id.llBtn2:
                onBackPressed();
                break;
            default:
                break;
        }
    }

    /**
     * (기존)비밀번호 확인(비밀번호 정보를 확인한다) 요청.
     */
    private void sendPostMemberPasswordExist() {

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

                    resultPostMemberPasswordExist(result);
                }
            });

            //공통 변수 입력
            httpSend.postMemberPasswordExist(mPassword.getText().toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        try {
            if (response.getStatusCode() == 200) {
                mIntent = new Intent(mActivity, SettingPasswordChange.class);
                mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_SETTING_PASSWORD_CHANGE);
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
//                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));
                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);
        }
        try {
            mOk.setEnabled(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {

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

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_SETTING_PASSWORD_CHANGE:
                    mIntent = new Intent();
                    mActivity.setResult(RESULT_OK, mIntent);
                    finish();
                    break;
                case Constants.ACT_SETTING_HOME_DEL:
                    mIntent = new Intent();
                    mActivity.setResult(RESULT_OK, mIntent);
                    finish();
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_SETTING_ACCOUNT_DEL_CONFIRM:
                case Constants.ACT_SETTING_PASSWORD_CHANGE:
                    mIntent = new Intent();
                    mActivity.setResult(RESULT_OK, mIntent);
                    finish();
                    break;
                default:
                    break;
            }
        }
    }

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

        switch (msgId) {

            case Constants.MSG998:
                mUtil.callApp_Start(mActivity, "LOGOUT");
                break;
            case Constants.MSG997:
                mUtil.callApp_Start(mActivity, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(mTag), Constants.HANDLER_DELAY_MILLIS);
                }
                break;
            default:
                break;
        }
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mTag = msg.what;
            switch (msg.what) {
                case MSG_COM_P_MEMBER_PASSWORD_EXIST:
                    sendPostMemberPasswordExist();
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}
