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

package com.ntels.kneet.v3.view;

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.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import android.widget.Toast;

import com.ntels.kneet.v3.R;
import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
import com.ntels.kneet.v3.common.http.HttpSend;
import com.ntels.kneet.v3.common.http.Response;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.common.widget.CustomActionBarActivity;
import com.ntels.kneet.v3.view.dialog.CustomDialog;

import org.json.JSONObject;

public class Join extends CustomActionBarActivity implements View.OnClickListener,
                                                             CustomDialog.OnMsgAlterToResult {

    private Toolbar toolbar;
    private Activity  act;
    private Intent    intent;
    private AppConfig appConfig;
    private              Util              util             = new Util();
    private              CustomDialog      customDialog     = new CustomDialog();
    private              int               iType            = 0;
    private              String            sName            = "";
    private              String            sId              = "";
    private              String            sPassCon         = "";
    private              String            sPass            = "";
    private              String            sFileName        = "";
    private static final int               MSG_COM_P_MEMBER = 1;

    /**
     * <PRE>
     * 1. MethodName: onCreate
     * 2. ClassName :
     * 3. Comment   : onCreate
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        act = Join.this;
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

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

        setToolbar();

        displayListView();
    }

    private void setToolbar() {

        toolbar = (Toolbar) act.findViewById(R.id.toolbar);
        util.setKeyboardHide(act, toolbar);
        util.getTextView(toolbar, R.id.tvToolbarTitle1).setVisibility(View.VISIBLE);
        util.getTextView(toolbar, R.id.tvToolbarTitle2).setVisibility(View.GONE);
        util.getTextView(toolbar, R.id.tvToolbarTitleDivider).setVisibility(View.GONE);
        util.getTextView(toolbar, R.id.tvToolbarTitle3).setVisibility(View.GONE);
        util.getTextView(toolbar, R.id.tvToolbarTitle4).setVisibility(View.GONE);
        util.getTextView(toolbar, R.id.btnToolbarDel).setVisibility(View.GONE);
        util.getTextView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
        util.getTextView(toolbar, R.id.btnToolbarMore).setVisibility(View.GONE);

        util.getTextView(toolbar, R.id.tvToolbarTitle1).setText(util.getString(act, R.string.layout_join_01));
    }

    private void displayListView() {

        util.getView(act, R.id.llBtn1).setOnClickListener(this);
        util.getView(act, R.id.llBtn2).setOnClickListener(this);
        util.getView(act, R.id.rlMemberImage).setOnClickListener(this);

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

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

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

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

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

    @Override public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    @Override public void onClick(View v) {

        Intent intent;
        switch (v.getId()) {
            case R.id.llBtn1:
                v.setEnabled(false);
                sName = util.getEditTextVal(act, R.id.edtName).trim();
                sPass = util.getEditTextVal(act, R.id.edtPass).trim();
                sPassCon = util.getEditTextVal(act, R.id.edtPassConfirm).trim();
                sId = util.getEditTextVal(act, R.id.edtId).trim();

                if ( !checkFormValid() ) {
                    v.setEnabled(true);
                    return;
                }

                ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_P_MEMBER), 10);
                v.setEnabled(true);
                break;
            case R.id.llBtn2:
                onBackPressed();
                break;
            case R.id.rlMemberImage:
                intent = new Intent(act, Image_Select.class);
                intent.putExtra(Constants.EXTRA_CROP_TYPE, true);
                util.callActivityForResultNoAnim(act, intent, Constants.ACT_IMAGE_SELECT);
                break;
            default:
                break;
        }
    }

    private Boolean checkFormValid() {

        Boolean bCheck = true;
        if ( sName.trim().length() < 1 ) {
            bCheck = false;
            util.setShowToast(act, util.getString(act, R.string.layout_join_02) + util.getString(act, R.string.MSG902), Toast.LENGTH_SHORT);
            return bCheck;
        }

        if ( sId.trim().length() < 1 ) {
            bCheck = false;
            util.setShowToast(act, util.getString(act, R.string.layout_join_03) + util.getString(act, R.string.MSG902), Toast.LENGTH_SHORT);
            return bCheck;
        }
        if ( sPass.trim().length() < 8 ) {
            bCheck = false;
            util.setShowToast(act, util.getString(act, R.string.layout_join_04) + util.getString(act, R.string.MSG901), Toast.LENGTH_SHORT);
            return bCheck;
        }

        if ( sPassCon.trim().length() < 8 ) {
            bCheck = false;
            util.setShowToast(act, util.getString(act, R.string.layout_join_06) + util.getString(act, R.string.MSG902), Toast.LENGTH_SHORT);
            return bCheck;
        }

        if ( !sPass.trim().equals(sPassCon.trim()) ) {
            bCheck = false;
            util.setShowToast(act, util.getString(act, R.string.MSG863), Toast.LENGTH_SHORT);
            return bCheck;
        }

        return bCheck;
    }

    Handler ComHandler = new Handler(new IncomingHandlerCallBack());

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override public boolean handleMessage(Message msg) {

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

    private void send_P_member() {

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

                    result_P_member(result);
                }
            });
            httpSend.P_member(sName, sId, sPass, appConfig.getService_Id(), Constants.OS_TYPE, appConfig.getCountry_Id(), appConfig.getTimezone_Id(), Constants.HTTP_image_file, sFileName);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void result_P_member(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {

                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());
                customDialog.MsgAlert(act, Constants.MSG828, sId, R.string.MSG_TITLE_001);
            } else {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());
                String sERR_CODE = util.null2string(joResult.get(Constants.HTTP_err_code));
                String sERR_MSG = util.null2string(joResult.get(Constants.HTTP_err_msg));

                if ( sERR_CODE.equals("401") ) {
                    customDialog.MsgAlert(act, Constants.MSG998, sERR_MSG);
                } else if ( sERR_CODE.equals("401-106") ) {
                    customDialog.MsgAlert(act, Constants.MSG997, sERR_MSG);
                } else {
                    customDialog.MsgAlert(act, Constants.MSG000, sERR_MSG);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.MsgAlert(act, Constants.MSG807);
        }

        try {
            util.getView(act, R.id.llBtn1).setEnabled(true);
        } catch (Exception ex) {

        }
    }

    /**
     * <PRE>
     * 1. MethodName: onBackPressed
     * 2. ClassName :
     * 3. Comment   : onBackPressed
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onBackPressed() {

        intent = new Intent();
        act.setResult(RESULT_CANCELED, intent);
        finish();
        return;
    }

    /**
     * <PRE>
     * 1. MethodName: onResume
     * 2. ClassName :
     * 3. Comment   : onResume
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onResume() {

        super.onResume();

    }

    @Override public void resultCustomDialogResponse(int iMsgID, int iBtnResult) {

        switch (iMsgID) {

            case Constants.MSG998:
                util.callApp_Start(act, "LOGOUT");
                break;
            case Constants.MSG997:
                util.callApp_Start(act, "HOME_RELOAD");
                break;
            case Constants.MSG828:
                if ( iBtnResult == 1 ) {
                    intent = new Intent();
                    act.setResult(RESULT_OK, intent);
                    finish();
                }
                break;
            case Constants.MSG807:
                if ( iBtnResult == 1 ) {
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(iType), 10);
                }
                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:
                    sFileName = util.null2string(data.getStringExtra(Constants.EXTRA_IMAGE_FILE_NAME));
                    util.setRefreshImage(act, sFileName, R.id.ivMemberIcon);
                    break;
                default:
                    break;
            }
        } else {
            if ( appConfig.getGoErr() ) {
                appConfig.setGoErr(true);
                setResult(RESULT_CANCELED, new Intent());
                finish();
            } else {
                switch (requestCode) {
                    default:
                        break;
                }
            }
        }
    }
}
