/*
 * 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.CustomActionBarActivity;
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.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

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

    private static final int MSG_COM_P_MEMBER_PASSWORD = 1;

    private Activity mAct;
    private Intent mIntent;
    private AppConfig mAppConfig;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private int mType = 0;
    private String mEmailId = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mAct = ResetPassword.this;
        mAppConfig = (AppConfig) mAct.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);

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

        setToolbar();

        displayListView();
    }

    @Override
    public void onResume() {

        super.onResume();
    }

    @Override
    public void onBackPressed() {

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

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btnSendEmail:
                Uri uri = Uri.parse("mailto:help@allofthings.com");
                Intent it = new Intent(Intent.ACTION_SENDTO, uri);
                startActivity(it);
                break;
            case R.id.btnReceiverEmail:
                if (!checkFormValid()) {
                    return;
                }
                view.setEnabled(false);
                comHandler.sendMessageDelayed(comHandler.obtainMessage(
                        MSG_COM_P_MEMBER_PASSWORD), Constants.HANDLER_DELAY_MILLIS);
                break;
            case R.id.llBtn1:
                onBackPressed();
                break;
            default:
                break;
        }
    }

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

        switch (msgId) {

            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(mType),
                            Constants.HANDLER_DELAY_MILLIS);
                } else {
                    mAct.finish();
                }
                break;
            case Constants.MSG840:
                mAct.finish();
                break;
            default:
                break;
        }
    }

    Handler comHandler = 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_MEMBER_PASSWORD:
                    sendPostMemberPassword();
                    break;
                default:
                    break;
            }
            return true;
        }
    }

    /**
     * 툴바 셋팅.
     */
    private void setToolbar() {

        Toolbar toolbar = (Toolbar) mAct.findViewById(R.id.toolbar);
        mUtil.setKeyboardHide(mAct, 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.btnToolbarDel).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(
                mAct, R.string.layout_reset_password_01));
    }

    /**
     * UI display.
     */
    private void displayListView() {

        mUtil.getView(mAct, R.id.btnSendEmail).setOnClickListener(this);
        mUtil.getView(mAct, R.id.btnReceiverEmail).setOnClickListener(this);
        mUtil.getView(mAct, R.id.llBtn1).setOnClickListener(this);
    }

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

        Boolean isCheck = true;
        mEmailId = mUtil.getEditTextVal(mAct, R.id.edtEmail);
        if (mEmailId.trim().length() < 1) {
            isCheck = false;
            mUtil.setShowToast(mAct, mUtil.getString(mAct, R.string.layout_join_03)
                    + mUtil.getString(mAct, R.string.MSG902), Toast.LENGTH_SHORT);
            return isCheck;
        }

        return isCheck;
    }

    /**
     * <pre>
     * 비밀번호 찾기(재설정) 요청.
     * (입력된 이메일 ID 정보로 비밀번호 찾기를 위한 메일 발송을 처리한다)
     * </pre>
     */
    private void sendPostMemberPassword() {

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

                    resultPostMemberPassword(result);
                }
            });
            httpSend.P_member_password(mEmailId, mAppConfig.getService_Id());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 비밀번호 찾기(재설정) 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultPostMemberPassword(Response result) {

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

                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                mCustomDialog.msgAlert(mAct, Constants.MSG840);
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));

                mCustomDialog.msgAlert(mAct, Constants.MSG000, errorMsg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mAct, Constants.MSG807);
        }
    }

}
