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

package com.ntels.onecable.view;

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.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 :   FindId1st
 * 2. FileName  :   FindId1st.java
 * 3. Package   :   com.ntels.onecable.view
 * 4. Date      :   2016-11-28
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class FindId1st extends CustomActivity implements View.OnClickListener,
        CustomDialog.OnMsgAlterToResult {

    private static final int MSG_COM_P_FIND_ID = 1;

    private static final String FIND_ID_CURRENT_STEP = "1";

    private Activity mActivity;
    private Intent mIntent;
    private AppConfig mAppConfig;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private int mType = 0;

    @BindView(R.id.edtCustId) EditText mCustId;
    @BindView(R.id.edtCellphone) EditText mCellphone;
    @BindView(R.id.llBtn1) LinearLayout mNext;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

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

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

        ButterKnife.bind(this);

        setToolbar();
        displayListView();
    }

    @Override
    public void onBackPressed() {

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_FIND_ID_2ND:
                    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.llBtn1, R.id.llBtn2})
    public void onClick(View view) {

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

    @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);
                } else {
                    mActivity.finish();
                }
                break;
            case Constants.MSG840:
                mActivity.finish();
                break;
            default:
                break;
        }
    }

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

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_P_FIND_ID:
                    sendPostFindId();
                    break;
                default:
                    break;
            }
            return true;
        }
    }

    /**
     * 툴바 셋팅.
     */
    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.getView(toolbar, R.id.llJoinStep).setVisibility(View.VISIBLE);
        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_find_id_1st_01));
        mUtil.getTextView(toolbar, R.id.tvCurrentStep).setText(FIND_ID_CURRENT_STEP);
        mUtil.getTextView(toolbar, R.id.tvTotalStep).setText(Constants.FIND_ID_TOTAL_STEP);
    }

    /**
     * UI display.
     */
    private void displayListView() {
        mNext.setEnabled(false);
        mCustId.addTextChangedListener(mTextWatcher);
        mCellphone.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) {
            checkFormValid();
        }
    };

    /**
     * 사용자 입력 필드 체크.
     *
     * @return 체크 결과
     */
    private void checkFormValid() {

        boolean isEnable = true;

        isEnable &= mCustId.length() > 0;
        isEnable &= mCellphone.length() >= 10;

        mNext.setEnabled(isEnable);
    }

    /**
     * <pre>
     * 아이디 찾기 요청.
     * </pre>
     */
    private void sendPostFindId() {

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

                    resultPostFindId(result);
                }
            });
            httpSend.postFindId(mCustId.getText().toString(), mCellphone.getText().toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 아이디 찾기 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultPostFindId(Response result) {

        try {
            if (result.getStatusCode() == Response.OK) {

                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String loginId = mUtil.null2string(joResult.get(Constants.KEY_MEMBER_ID));
                String nickname = mUtil.null2string(joResult.get(Constants.KEY_NICKNAME));
                mIntent = new Intent(mActivity, FindId2nd.class);
                mIntent.putExtra(Constants.EXTRA_MEMBER_ID, loginId);
                mIntent.putExtra(Constants.EXTRA_NICKNAME, nickname);
                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_FIND_ID_2ND);
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                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);
        }
    }

}
