/*
 * 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 android.widget.Toast;

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

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

    private static final int MSG_COM_P_MEMBER_INFO = 1;
    Handler comHandler = 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();
    @BindView(R.id.edtPass) EditText mPassword;
    @BindView(R.id.edtPassConfirm) EditText mPasswordConfirm;
    @BindView(R.id.llBtn1) LinearLayout mOk;


    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

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

        View viewToLoad = LayoutInflater.from(mActivity).inflate(R.layout.setting_password_change, 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_change_01));
    }

    private void displayView() {
        mOk.setEnabled(false);
        mPassword.addTextChangedListener(mTextWatcher);
        mPasswordConfirm.addTextChangedListener(mTextWatcher);
    }

    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) {
            checkEnable();
        }
    };

    /**
     * 조건 체크하여 확인버튼 활성화.
     */
    private void checkEnable() {
        boolean isEnable = true;
        isEnable &= mPassword.length() >= 8;
        isEnable &= mPasswordConfirm.length() >= 8;
        isEnable &= mPassword.getText().toString().equals(mPasswordConfirm.getText().toString());

        mOk.setEnabled(isEnable);
    }

    @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);
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_P_MEMBER_INFO), Constants.HANDLER_DELAY_MILLIS);
                break;
            case R.id.llBtn2:
                onBackPressed();
                break;
            default:
                break;
        }
    }

    /**
     * 회원 정보 수정(비밀번호 정보에 대해 변경 처리한다) 요청.
     */
    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_PASSWORD, mPasswordConfirm.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.MSG927), 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.MSG998:
                mUtil.callApp_Start(mActivity, "LOGOUT");
                break;
            case Constants.MSG997:
                mUtil.callApp_Start(mActivity, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.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_MEMBER_INFO:
                    sendPutMemberInfo();
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}
