/*
 * 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.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import android.widget.Toast;

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

    private static final int MSG_COM_P_MEMBER = 1;
    private static final int PASSWORD_MIN_LENGTH = 8;
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    private Activity mActivity;
    private Intent mIntent;
    private AppConfig mAppConfig;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private int mType = 0;
    private String mName = "";
    private String mId = "";
    private String mPassCon = "";
    private String mPass = "";
    private String mFileName = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

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

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

        setToolbar();

        displayListView();
    }

    @Override
    public void onBackPressed() {

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

    @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.MSG828:
                if (btnResult == 1) {
                    mIntent = new Intent();
                    mActivity.setResult(RESULT_OK, mIntent);
                    finish();
                }
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(mType),
                            Constants.HANDLER_DELAY_MILLIS);
                }
                break;
            default:
                break;
        }
    }

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

        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_ERROR_PAGE:
                    break;
                case Constants.ACT_IMAGE_SELECT:
                    mFileName =
                            mUtil.null2string(data.getStringExtra(Constants.EXTRA_IMAGE_FILE_NAME));
                    mUtil.setRefreshImage(mActivity, mFileName, R.id.ivMemberIcon);
                    break;
                default:
                    break;
            }
        } else {
            if (mAppConfig.getGoErr()) {
                mAppConfig.setGoErr(true);
                setResult(RESULT_CANCELED, new Intent());
                finish();
            } else {
                switch (requestCode) {
                    default:
                        break;
                }
            }
        }
    }

    @Override
    public void onClick(View view) {

        Intent intent;
        switch (view.getId()) {
            case R.id.llBtn1:
                view.setEnabled(false);
                mName = mUtil.getEditTextVal(mActivity, R.id.edtName).trim();
                mPass = mUtil.getEditTextVal(mActivity, R.id.edtPass).trim();
                mPassCon = mUtil.getEditTextVal(mActivity, R.id.edtPassConfirm).trim();
                mId = mUtil.getEditTextVal(mActivity, R.id.edtId).trim();

                if (!checkFormValId()) {
                    view.setEnabled(true);
                    return;
                }

                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_P_MEMBER),
                        Constants.HANDLER_DELAY_MILLIS);
                view.setEnabled(true);
                break;
            case R.id.llBtn2:
                onBackPressed();
                break;
            case R.id.rlMemberImage:
                intent = new Intent(mActivity, ImageSelect.class);
                intent.putExtra(Constants.EXTRA_CROP_TYPE, true);
                mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_IMAGE_SELECT);
                break;
            default:
                break;
        }
    }

    /**
     * 툴바 셋팅.
     */
    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.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(mActivity, R.string.layout_join_01));
    }

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

        mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llBtn2).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.rlMemberImage).setOnClickListener(this);

        mUtil.setKeyboardHide(mActivity, mUtil.getLinearLayout(mActivity, R.id.llSvbody));
        mUtil.getEditText(mActivity, R.id.edtName).setOnEditorActionListener(
                new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {

                        switch (actionId) {
                            case EditorInfo.IME_ACTION_DONE:
                                break;
                            default:
                                return false;
                        }
                        return false;
                    }
                });
        mUtil.getEditText(mActivity, R.id.edtId).setOnEditorActionListener(
                new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {

                        switch (actionId) {
                            case EditorInfo.IME_ACTION_DONE:
                                break;
                            default:
                                return false;
                        }
                        return false;
                    }
                });
        mUtil.getEditText(mActivity, R.id.edtPass).setOnEditorActionListener(
                new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {

                        switch (actionId) {
                            case EditorInfo.IME_ACTION_DONE:
                                break;
                            default:
                                return false;
                        }
                        return false;
                    }
                });
        mUtil.getEditText(mActivity, R.id.edtPassConfirm).setOnEditorActionListener(
                new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {

                        switch (actionId) {
                            case EditorInfo.IME_ACTION_DONE:
                                break;
                            default:
                                return false;
                        }
                        return false;
                    }
                });
    }

    /**
     * ID & Password 체크.
     *
     * @return 체크 결과
     */
    private Boolean checkFormValId() {

        Boolean isCheck = true;
        if (mName.trim().length() < 1) {
            isCheck = false;
            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.layout_join_02)
                    + mUtil.getString(mActivity, R.string.MSG902), Toast.LENGTH_SHORT);
            return isCheck;
        }

        if (mId.trim().length() < 1) {
            isCheck = false;
            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.layout_join_03)
                    + mUtil.getString(mActivity, R.string.MSG902), Toast.LENGTH_SHORT);
            return isCheck;
        }
        if (mPass.trim().length() < PASSWORD_MIN_LENGTH) {
            isCheck = false;
            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.layout_join_04)
                    + mUtil.getString(mActivity, R.string.MSG901), Toast.LENGTH_SHORT);
            return isCheck;
        }

        if (mPassCon.trim().length() < PASSWORD_MIN_LENGTH) {
            isCheck = false;
            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.layout_join_06)
                    + mUtil.getString(mActivity, R.string.MSG902), Toast.LENGTH_SHORT);
            return isCheck;
        }

        if (!mPass.trim().equals(mPassCon.trim())) {
            isCheck = false;
            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG863),
                    Toast.LENGTH_SHORT);
            return isCheck;
        }

        return isCheck;
    }

    /**
     * 회원 가입 등록(회원 가입 정보를 입력 완료 후 인증 이메일을 발송한다) 요청.
     */
    private void sendPostMember() {

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

                    resultPostMember(result);
                }
            });
            httpSend.P_member(mName, mId, mPass, mAppConfig.getService_Id(), Constants.OS_TYPE,
                    mAppConfig.getCountry_Id(), mAppConfig.getTimezone_Id(), Constants.KEY_IMAGE_FILE, mFileName);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 회원 가입 등록(회원 가입 정보를 입력 완료 후 인증 이메일을 발송한다) 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultPostMember(Response result) {

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

                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                mCustomDialog.msgAlert(mActivity, Constants.MSG828, mId, R.string.MSG_TITLE_001);
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));

                if ("401".equals(errorCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG998, errorMsg);
                } else if ("401-106".equals(errorCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG997, errorMsg);
                } else {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, errorMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }

        try {
            mUtil.getView(mActivity, R.id.llBtn1).setEnabled(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

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

}
