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

package com.ntels.onecable.admin.view;

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.db.DatabaseOpenHelper;
import com.ntels.onecable.admin.common.db.SqlManager;
import com.ntels.onecable.admin.common.handler.BackPressCloseHandler;
import com.ntels.onecable.admin.common.handler.CallWithDelayHandler;
import com.ntels.onecable.admin.common.util.Dlog;
import com.ntels.onecable.admin.common.util.Util;
import com.ntels.onecable.admin.common.websocket.WebSocketService;
import com.ntels.onecable.admin.common.widget.CustomActivity;
import com.ntels.onecable.admin.view.dialog.CustomDialog;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import java.util.HashMap;

import static com.ntels.onecable.admin.common.Constants.EXTRA_ERROR_CODE;
import static com.ntels.onecable.admin.common.Constants.EXTRA_RESULT_STATE;
import static com.ntels.onecable.admin.common.broadcast.DefaultLocalBroadCast.INTENT_NAME_TYPE;


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

    private static final int MSG_COM_P_MEMBER_LOGIN = 1;
    private static final int MSG_COM_G_MEMBER = 2;
    private static final int VIBRATION_DURATION = 100;
    private static final int FINISH_INTERVAL = 1000;
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    private BackPressCloseHandler mBackPressCloseHandler;
    private int mType = 0;
    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Intent mIntent;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private SqlManager mSqlManager = new SqlManager();
    private Boolean mIsExit = false;    // 종료여부 묻기 플래그
    private Boolean mIsAutoLogin = false;
    private Boolean mIsSaveId = false;
    private String mId = "";
    private String mPass = "";
    private String mPushTypeCode = "";

    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) {

            String id = mUtil.getEditText(mActivity, R.id.edtId).getText().toString();
            String pass = mUtil.getEditText(mActivity, R.id.edtPass).getText().toString();

            if (mUtil.null2string(id).length() > 0 && mUtil.null2string(pass).length() > 0) {
                mUtil.getView(mActivity, R.id.btnLogin).setEnabled(true);
            } else {
                mUtil.getView(mActivity, R.id.btnLogin).setEnabled(false);
            }
        }
    };

    @Override
    protected void onNewIntent(Intent saveIntent) {

        super.onNewIntent(saveIntent);
        Dlog.v("jinointent");
        if (null != saveIntent) {
            mPushTypeCode = "";
            mPushTypeCode = mUtil.null2string(saveIntent.getStringExtra(Constants.EXTRA_PUSH_TYPE_CODE));
            Dlog.v(mPushTypeCode);

            if (saveIntent.hasExtra(Constants.EXTRA_BUNDLE_DATA)) {
                Bundle receivedData = saveIntent.getBundleExtra(Constants.EXTRA_BUNDLE_DATA);
                Intent intentReceived = new Intent();

                intentReceived.putExtras(receivedData);
                String nameType = intentReceived.getStringExtra(INTENT_NAME_TYPE);

//                if (nameType.equals(KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE)) {

//                } else if (nameType.equals(KneetMessageLocalBroadCast.INTENT_ACTION_WEBSOCKET_MSG_RECEIVED)) {
//                    recevicedWebSocket(intentReceived);
//                }
            }
        }
    }

    public void recevicedWebSocket(Intent intentReceived) {

        int receivedState = intentReceived.getIntExtra(EXTRA_RESULT_STATE, WebSocketService.WEBSOCKET_RECEIVED_SUCESS);
        if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_SUCESS) {
            try {
                String result = intentReceived.getStringExtra(Constants.EXTRA_RESULT);
                Dlog.v(result);
                final JSONObject jsonObject = new JSONObject(result);
                final String messageType = mUtil.null2string(jsonObject.get(Constants.KEY_MESSAGE_TYPE));
                Dlog.i("websocket message mType : " + messageType);
                String resultCode = "";
                String resultMsg = "";
                if (jsonObject.has(Constants.KEY_RESULT_CODE)) {
                    resultCode = mUtil.null2string(jsonObject.get(Constants.KEY_RESULT_CODE));
                }
                if (jsonObject.has(Constants.KEY_RESULT_MSG)) {
                    resultMsg = mUtil.null2string(jsonObject.get(Constants.KEY_RESULT_MSG));
                }

//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
                if (messageType.equals(Constants.WEBSOCKET_TYPE_AUTH_INSTALLER)) {
                    resultWsAuthInstaller(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_AUTH_INSTALLER_AUTO)) {
                    resultWsAuthInstaller(jsonObject);
                } else {

//                                    final String finalResultMsg = resultMsg;
//                                    runOnUiThread(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            mUtil.setShowToast(mActivity, finalResultMsg, Toast.LENGTH_SHORT);
//                                        }
//                                    });
                }
//                                }
//                            });
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        } else if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_ERROR) {

            int errorCode = intentReceived.getIntExtra(EXTRA_ERROR_CODE, WebSocketService.WEBSOCKET_CONNECT_TIMEOUT);
            switch (errorCode) {
//                            case Constants.WEBSOCKET_ERROR_TIMEOUT:
//                                Dlog.i("WEBSOCKET_ERROR_TIMEOUT!!!");
//                                for (HashMap<String, Object> hm : alTotalList) {
//                                    hm.put(Constants.KEY_REQUEST_TIME, "");
//                                }
//                                break;
                case Constants.WEBSOCKET_ERROR_NOT_CONNECTED:
                    Dlog.i("WEBSOCKET_ERROR_NOT_CONNECTED!!!");
                    mCustomDialog.msgAlert(mActivity, Constants.MSG807);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onResume() {
        Dlog.i("onResume()!!");

        super.onResume();
    }

    @Override
    protected void onPause() {

        super.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Dlog.v("onDestroy()");

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mActivity = Login.this;
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);
        mBackPressCloseHandler = new BackPressCloseHandler(this);

        setIsWebSocket(true);

        Dlog.v("mAppConfig.getIntro()=" + mAppConfig.getIntro());
        View viewToLoad = LayoutInflater.from(mActivity).inflate(R.layout.login, null);
        this.setContentView(viewToLoad);

        if (savedInstanceState != null) {
            mIsExit = savedInstanceState.getBoolean(Constants.EXTRA_EXIT_FLAG, false);
        } else {
            mIntent = getIntent();
            mIsExit = mIntent.getBooleanExtra(Constants.EXTRA_EXIT_FLAG, false);
            mPushTypeCode = mUtil.null2string(getIntent().getStringExtra(Constants.EXTRA_PUSH_TYPE_CODE));
        }

//        int height = mAppConfig.getDisplayHeight();
//        int tempHeight = (int) (height * 0.45);
//        LinearLayout.LayoutParams paramView3 = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.MATCH_PARENT, tempHeight);
//        mUtil.getView(mActivity, R.id.llbody1).setLayoutParams(paramView3);
//        mUtil.getView(mActivity, R.id.ivLogo).setLayoutParams(paramView3);

//        LinearLayout.LayoutParams paramView4 = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.MATCH_PARENT, height - tempHeight);
//        mUtil.getView(mActivity, R.id.llbody1).setLayoutParams(paramView4);
        mUtil.getView(mActivity, R.id.btnLogin).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.btnLogin).setEnabled(false);
        mUtil.getView(mActivity, R.id.llAutoLogin).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llSaveId).setOnClickListener(this);

        mUtil.getEditText(mActivity, R.id.edtId).setText("");
        mUtil.getEditText(mActivity, R.id.edtPass).setText("");
//        mUtil.getEditText(mActivity, R.id.edtId).setText("welove75");
//        mUtil.getEditText(mActivity, R.id.edtPass).setText("78980250");
        mUtil.getEditText(mActivity, R.id.edtId).addTextChangedListener(mTextWatcher);
        mUtil.getEditText(mActivity, R.id.edtPass).addTextChangedListener(mTextWatcher);

        mUtil.setUserInfo(mActivity);
        mIsSaveId = mAppConfig.getSaveId();
        mIsAutoLogin = mAppConfig.getIsAutoLogin();
        Dlog.v("mIsAutoLogin =" + mIsAutoLogin);
        Dlog.v("mIsSaveId =" + mIsSaveId);
        mUtil.getView(mActivity, R.id.llAutoLogin).setSelected(mIsAutoLogin);
        mUtil.getView(mActivity, R.id.llSaveId).setSelected(mIsSaveId);
        if (mIsAutoLogin) {
            mUtil.getView(mActivity, R.id.llRoot).setVisibility(View.INVISIBLE);
            mId = mAppConfig.getLoginId();
            mPass = "";
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
        } else {
            mUtil.getView(mActivity, R.id.llAutoLogin).performClick();
        }
        if (mIsSaveId) {
            mId = mAppConfig.getLoginId();
            if (!"".equals(mId)) {
                mUtil.getEditText(mActivity, R.id.edtId).setText(mId);
                mUtil.getEditText(mActivity, R.id.edtId).setSelection(mId.length());
            }
        }
        mUtil.setKeyboardHide(mActivity, mUtil.getLinearLayout(mActivity, R.id.llSvbody));

    }

    /**
     * 서비스허브에 노드 동기화를 요청한다.(데이터 동기화 아님)
     */

    private void sendWssTest() {

        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_AUTH);
        sendParams.put(Constants.KEY_MEMBER_ID, "100");
        sendParams.put(Constants.KEY_MEMBER_PASSWORD, "1234");
        sendParams.put(Constants.KEY_OS_TYPE, Constants.OS_TYPE);
        sendParams.put(Constants.KEY_CUST_ID, "1002");
        sendParams.put(Constants.KEY_CTRT_GRP_ID, "1002");
        getWebSocketService().send(Constants.WEBSOCKET_SEND_AUTH, sendParams);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {

        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            mIsExit = savedInstanceState.getBoolean(Constants.EXTRA_EXIT_FLAG, false);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
        outState.putBoolean(Constants.EXTRA_EXIT_FLAG, mIsExit);
    }

    @Override
    public void onBackPressed() {

        mBackPressCloseHandler.onBackPressed("setExit");
    }

    @Override
    public void setAnimFinish(String val) {

        super.setAnimFinish(val);
    }

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

        super.onActivityResult(requestCode, resultCode, data);
        Boolean isReload = false;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_ERROR_PAGE:
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(mType),
                            Constants.HANDLER_DELAY_MILLIS);
                    break;
                case Constants.ACT_JOIN_STEP_2ND:
                    //setFinish();
                    break;
                case Constants.ACT_LOGIN_NEW_DEVICE:
                    isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
                    } else {
                        setFinish();
                    }
                    break;
                case Constants.ACT_INVITATION_LIST:
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_MEMBER),
                            Constants.HANDLER_DELAY_MILLIS);
                    break;
                default:
                    break;
            }
        } else {
            if (mAppConfig.getGoErr()) {
                setExit();
            } else {
                switch (requestCode) {
                    case Constants.ACT_INVITATION_LIST:
                        setFinish();
                        break;
                    default:
                        break;
                }
            }
        }
    }

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

        switch (msgId) {
            case Constants.MSG801:
                if (btnResult == 1) {
                    Dlog.v("jino test");
                }
                break;
            case Constants.MSG804:
                if (btnResult == 1) {
                    setExit();
                }
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(mType), Constants.HANDLER_DELAY_MILLIS);
                } else {
                    setExit();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llAutoLogin:
                if (mIsAutoLogin) {
                    mIsAutoLogin = false;
                } else {
                    mIsAutoLogin = true;
                }
                mUtil.getView(mActivity, R.id.llAutoLogin).setSelected(mIsAutoLogin);
                break;
            case R.id.llSaveId:
                if (mIsSaveId) {
                    mIsSaveId = false;
                } else {
                    mIsSaveId = true;
                }
                mUtil.getView(mActivity, R.id.llSaveId).setSelected(mIsSaveId);
                break;
            case R.id.btnLogin:
                mPass = "";
                mPass += mUtil.getEditTextVal(mActivity, R.id.edtPass).trim();
                mId = "";
                mId += mUtil.getEditTextVal(mActivity, R.id.edtId).trim();

                if (!checkFormValid()) {
                    mUtil.setShowToast(mActivity,
                            mUtil.getString(mActivity, R.string.MSG802), Toast.LENGTH_SHORT);
                    return;
                }
                mUtil.setVibrator(VIBRATION_DURATION);
                view.setEnabled(false);
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_P_MEMBER_LOGIN), Constants.HANDLER_DELAY_MILLIS);
                break;
            default:
                break;
        }
    }

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

        Boolean isCheck = true;

        if (mId.trim().length() < 1) {
            isCheck = false;
        }
        if (mPass.trim().length() < 1) {
            isCheck = false;
        }
        return isCheck;
    }

    /**
     * 멤버 로그인 요청.
     */
    private void sendWsMemberAuthInstaller() {

        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_AUTH_INSTALLER);
        sendParams.put(Constants.KEY_INSTALLER_ID, mId);
        sendParams.put(Constants.KEY_PASSWORD, mPass);
        sendParams.put(Constants.KEY_OS_TYPE, Constants.OS_TYPE);
        sendParams.put(Constants.KEY_DEVICE_TOKEN, mAppConfig.getPush_Token());
        sendParams.put(Constants.KEY_REQUEST_ID, mAppConfig.getSelectServicehubRequestId());
        Dlog.v(sendParams);
        getWebSocketService().send(Constants.WEBSOCKET_SEND_AUTH_INSTALLER, sendParams);
    }

    /**
     * 자동로그인  로그인 요청.
     */
    private void sendWsMemberAuthInstallerAuto() {

        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_AUTH_INSTALLER_AUTO);
        sendParams.put(Constants.KEY_AUTHORIZATION, mAppConfig.getAuthorization());
        sendParams.put(Constants.KEY_OS_TYPE, Constants.OS_TYPE);
        sendParams.put(Constants.KEY_DEVICE_TOKEN, mAppConfig.getPush_Token());
        sendParams.put(Constants.KEY_REQUEST_ID, mAppConfig.getSelectServicehubRequestId());
        Dlog.v(sendParams);
        getWebSocketService().send(Constants.WEBSOCKET_SEND_AUTH_INSTALLER_AUTO, sendParams);
    }

    /**
     * 멤버 로그인 요청 결과.
     *
     * @param jsonObject 결과 data
     */
    private void resultWsAuthInstaller(JSONObject jsonObject) {

        Dlog.i("resultWsAuth!!");

        try {
            JSONObject joResult = jsonObject;
            Dlog.v(joResult.toString());

            String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));

            if ("00".equals(resultCode)) {

                //request ID
                String requestId = "";
                if (joResult.has(Constants.KEY_REQUEST_ID)) {
                    requestId = mUtil.null2string(joResult.get(Constants.KEY_REQUEST_ID));
                }

                //인증 토큰
                String authToken = "";
                if (joResult.has(Constants.KEY_AUTH_TOKEN)) {
                    authToken = mUtil.null2string(joResult.get(Constants.KEY_AUTH_TOKEN));
                } else {
                    authToken = mAppConfig.getAuthToken();
                }

                mAppConfig.setIsLogin(true);
                mAppConfig.setIsAutoLogin(mIsAutoLogin);
                mAppConfig.setSaveId(mIsSaveId);
                mAppConfig.setLoginId(mId);
                mAppConfig.setAuthToken(authToken);

                //db 입력작업
                SQLiteDatabase db = DatabaseOpenHelper.getInstance(mActivity).getWritableDatabase();
                String sql = "";
                sql = mSqlManager.qryDelLoginInfo();
                db.execSQL(sql);

                sql = "";
                Dlog.v("mIsAutoLogin =" + mIsAutoLogin);
                sql = mSqlManager.qryInsertLoginInfo(mId, authToken, mIsSaveId, mIsAutoLogin, mAppConfig.getManualNotView(),
                        mAppConfig.getPush());
                db.execSQL(sql);
                db.close();

                setFinish();
                return;
            } else {
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));
                if ("71".equals(resultCode)) {
                    mUtil.getView(mActivity, R.id.llRoot).setVisibility(View.VISIBLE);
                    mCustomDialog.msgAlert(mActivity, Constants.MSG924);
                } else if ("401".equals(resultCode)) {
                    mUtil.getView(mActivity, R.id.llRoot).setVisibility(View.VISIBLE);
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                } else if ("401-101".equals(resultCode)) {
                    mUtil.getView(mActivity, R.id.llRoot).setVisibility(View.VISIBLE);
                    mCustomDialog.msgAlert(mActivity, Constants.MSG828, mId, R.string.MSG_TITLE_001);
                } else {
                    mUtil.getView(mActivity, R.id.llRoot).setVisibility(View.VISIBLE);
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mUtil.getView(mActivity, R.id.llRoot).setVisibility(View.VISIBLE);
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }

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

    /**
     * 종료 후 메인으로 이동.
     */
    private void setFinish() {

        Intent intent = new Intent(mActivity, Main.class);
        intent.putExtra(Constants.EXTRA_PUSH_TYPE_CODE, "");
        mUtil.callActivityNoAnim(mActivity, intent);

        setFinishLoading();
    }

    /**
     * 로딩 완료.
     */
    public void setFinishLoading() {
        new CallWithDelayHandler(this).callFinishWithDelay("isFinish");
    }

    private Boolean isFinish() {
        if (!mAppConfig.getMain()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * App 종료.
     */
    public void setExit() {

        Dlog.v("setExit()");
        mAppConfig.setIntro(false);
        mAppConfig.setGoErr(false);
        mAppConfig.setMain(false);
        setResult(RESULT_CANCELED, new Intent());
        getWebSocketService().webSocketDisconnect();
        finish();
    }


    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_P_MEMBER_LOGIN:
//                    sendWsMemberAuth();
                    new CallWithDelayHandler(mActivity).callWithDelay("getWebSocketState", "sendWsMemberAuthInstaller");
                    break;
                case MSG_COM_G_MEMBER:
                    // 추후 바
//                    sendWsMemberAuth();
                    new CallWithDelayHandler(mActivity).callWithDelay("getWebSocketState", "sendWsMemberAuthInstallerAuto");
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}
