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

package com.ntels.kneet.v3.view;

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.db.DatabaseOpenHelper;
import com.ntels.kneet.v3.common.db.SqlManager;
import com.ntels.kneet.v3.common.gcm.support.KneetMessageLocalBroadCast;
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.CustomActivity;
import com.ntels.kneet.v3.view.dialog.CustomDialog;
import com.ntels.kneet.v3.view.invitation.InvitationList;

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.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

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

    private int mType = 0;
    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;

    /*공통*/
    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 String mId = "";
    private String mPass = "";
    private String mPushTypeCode = "";

    @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);
            Boolean isTemp = saveIntent.getBooleanExtra(
                    KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE, false);
            Dlog.v("isTemp", isTemp);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

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

        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.tvJoin).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.tvPassFind).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llAutoLogin).setOnClickListener(this);

        mUtil.getViewUnderline(mActivity, R.id.tvJoin);
        mUtil.getViewUnderline(mActivity, R.id.tvPassFind);

        mUtil.getEditText(mActivity, R.id.edtId).setText("");
        mUtil.getEditText(mActivity, R.id.edtPass).setText("");

        mUtil.setUserInfo(mActivity);
        mIsAutoLogin = mAppConfig.getAutoLogin();
        Dlog.v("mIsAutoLogin =" + mIsAutoLogin);
        mUtil.getView(mActivity, R.id.llAutoLogin).setSelected(mIsAutoLogin);
        if (mIsAutoLogin) {
            mUtil.getView(mActivity, R.id.llRoot).setVisibility(View.INVISIBLE);
            mId = mAppConfig.getLogin_Id();
            mPass = "";
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_MEMBER),
                    Constants.HANDLER_DELAY_MILLIS);
        } else {
            mUtil.getView(mActivity, R.id.llAutoLogin).performClick();
        }
        mUtil.setKeyboardHide(mActivity, mUtil.getLinearLayout(mActivity, R.id.llSvbody));

    }

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

        if (!isBackPress) {
            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG823),
                    Toast.LENGTH_SHORT);
            isBackPress = true;
            handler.sendEmptyMessageDelayed(0, BACK_PRESS_VALID_TIME);
        } else {
            setExit();
        }
    }

    Boolean isBackPress = false;

    @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:
                    //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_LOGIN_DEVICE_OVER:
                    mIntent = new Intent(mActivity, LoginNewDevice.class);
                    String emailId =
                            mUtil.null2string(data.getStringExtra(Constants.EXTRA_EMAIL_ID));
                    mIntent.putExtra(Constants.EXTRA_EMAIL_ID, emailId);
                    String nickname =
                            mUtil.null2string(data.getStringExtra(Constants.EXTRA_NICKNAME));
                    mIntent.putExtra(Constants.EXTRA_NICKNAME, nickname);
                    String deviceSn =
                            mUtil.null2string(data.getStringExtra(Constants.HTTP_device_sn));
                    mIntent.putExtra(Constants.HTTP_device_sn, deviceSn);
                    mUtil.callActivityForResultNoAnim(mActivity, mIntent,
                            Constants.ACT_LOGIN_NEW_DEVICE);
                    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.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;
            case R.id.tvJoin:
                mIntent = new Intent(mActivity, JoinCheck.class);
                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_JOIN_CHK);
                break;
            case R.id.tvPassFind:
                mIntent = new Intent(mActivity, ResetPassword.class);
                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_RESET_PASSWORD);
                break;
            default:
                break;
        }
    }

    Handler handler = new Handler(new FinishHandlerCallBack());

    class FinishHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            if (msg.what == 0) {
                isBackPress = false;
            }
            return true;
        }
    }

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

        Boolean isCheck = true;

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

    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_LOGIN:
                    sendPostMemberLogin();
                    break;
                case MSG_COM_G_MEMBER:
                    sendPutMemberAutoLogin();
                    break;
                default:
                    break;
            }
            return true;
        }
    }

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

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

                    resultMemberLogin(result);
                }
            });
            httpSend.P_member_login(mId, mPass, mAppConfig.getService_Id(), Constants.OS_TYPE,
                    mAppConfig.getUuid(), mAppConfig.getPush_Token(), mUtil.getPhoneName(),
                    mUtil.getHostName());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * <pre>
     * 멤버 자동 로그인 요청.
     * (인증 토큰을 기준으로 회원의 로그인 정보를 조회하고 푸시 토큰을 등록/수정한다)
     * </pre>
     */
    private void sendPutMemberAutoLogin() {

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

                    resultMemberLogin(result);
                }
            });

            //공통 변수 입력
            httpSend.P_member(mAppConfig.getUuid(), mAppConfig.getPush_Token(),
                    Constants.OS_TYPE, mUtil.getHostName());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 멤버 로그인 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultMemberLogin(Response result) {

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

                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());

                //회원이미지 추가
                String imageFileName;
                if (joResult.has(Constants.HTTP_image_file_name)) {
                    imageFileName = mUtil.null2string(joResult.get(Constants.HTTP_image_file_name));
                    mAppConfig.setMy_Image_Url(imageFileName);
                }
                //회원명
                String nickname;
                if (joResult.has(Constants.HTTP_nickname)) {
                    nickname = mUtil.null2string(joResult.get(Constants.HTTP_nickname));
                    mAppConfig.setNickname(nickname);
                }

                String tempPasswordYn = "";
                if (joResult.has(Constants.HTTP_temp_password_yn)) {
                    tempPasswordYn =
                            mUtil.null2string(joResult.get(Constants.HTTP_temp_password_yn));
                }
                mAppConfig.setTemp_Password_Yn(tempPasswordYn);

                String invitationsCount = "";
                if (joResult.has(Constants.HTTP_invitations_count)) {
                    invitationsCount =
                            mUtil.null2string(joResult.get(Constants.HTTP_invitations_count));
                }

                String homegrpId = "";
                if (joResult.has(Constants.HTTP_homegrp_id)) {
                    homegrpId = mUtil.null2string(joResult.get(Constants.HTTP_homegrp_id));
                }

                String homegrpImageFileName = "";
                if (joResult.has(Constants.HTTP_homegrp_image_file_name)) {
                    homegrpImageFileName = mUtil.null2string(joResult.get(
                            Constants.HTTP_homegrp_image_file_name));
                }

                String homegrpName = "";
                if (joResult.has(Constants.HTTP_homegrp_name)) {
                    homegrpName = mUtil.null2string(joResult.get(Constants.HTTP_homegrp_name));
                }

                String gradeCode = "";
                if (joResult.has(Constants.HTTP_grade_code)) {
                    gradeCode = mUtil.null2string(joResult.get(Constants.HTTP_grade_code));
                }

                String homehubDeviceId = "";
                if (joResult.has(Constants.HTTP_homehub_device_id)) {
                    homehubDeviceId =
                            mUtil.null2string(joResult.get(Constants.HTTP_homehub_device_id));
                }

                String homehubDeviceKey = "";
                if (joResult.has(Constants.HTTP_homehub_device_key)) {
                    homehubDeviceKey =
                            mUtil.null2string(joResult.get(Constants.HTTP_homehub_device_key));
                }

                String homehubConnState = "";
                if (joResult.has(Constants.HTTP_device_conn)) {
                    homehubConnState = mUtil.null2string(joResult.get(Constants.HTTP_device_conn));
                }

                String homehubDongleState = "";
                if (joResult.has(Constants.HTTP_device_online)) {
                    homehubDongleState =
                            mUtil.null2string(joResult.get(Constants.HTTP_device_online));
                }

                String servicehubApplicationId = "";
                if (joResult.has(Constants.HTTP_servicehub_app_id)) {
                    servicehubApplicationId = mUtil.null2string(
                            joResult.get(Constants.HTTP_servicehub_app_id));
                }

                String deviceOnlineLastDatetime = "";
                if (joResult.has(Constants.HTTP_device_online_last_datetime)) {
                    deviceOnlineLastDatetime = mUtil.null2string(
                            joResult.get(Constants.HTTP_device_online_last_datetime));
                }

                //회원 번호
                String memberId = mUtil.null2string(joResult.get(Constants.HTTP_member_id));
                mAppConfig.setLogin_Member_Id(memberId);
                //이메일 ID
                String emailId = mUtil.null2string(joResult.get(Constants.HTTP_email_id));
                mAppConfig.setLogin_Id(emailId);
                if ("Y".equals(tempPasswordYn)) {
                    mAppConfig.setLogin_Pass(mPass);
                } else {
                    mAppConfig.setLogin_Pass("");
                }
                mAppConfig.setAutoLogin(mIsAutoLogin);
                mAppConfig.setLogin(true);

                //인증 토큰
                String authToken = mUtil.null2string(joResult.get(Constants.HTTP_auth_token));
                //공통 변수 입력
                mAppConfig.setAuth_Token(authToken);

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

                sql = "";
                Dlog.v("mIsAutoLogin =" + mIsAutoLogin);
                Boolean isSaveId = false;
                sql = mSqlManager.qryInsertLoginInfo(emailId, authToken, isSaveId, mIsAutoLogin,
                        mAppConfig.getManualNotView(), mAppConfig.getPush());
                db.execSQL(sql);
                db.close();

                String pushTypeModeChgYn = mUtil.null2string(joResult.get(
                        Constants.HTTP_push_type_mode_chg_yn));
                mAppConfig.setPush_Type_Mode_Chg_Yn(pushTypeModeChgYn);
                String pushTypePrsncChgYn = mUtil.null2string(joResult.get(
                        Constants.HTTP_push_type_prsnc_chg_yn));
                mAppConfig.setPush_Type_Prsnc_Chg_Yn(pushTypePrsncChgYn);
                mAppConfig.setInvitations_Count(invitationsCount);
                mAppConfig.setSelect_Homegrp_Id(homegrpId);
                mAppConfig.setSelect_Homegrp_Icon(homegrpImageFileName);
                mAppConfig.setSelect_Homegrp_Name(homegrpName);
                mAppConfig.setSelect_Homegrp_Grade_Code(gradeCode);
                mAppConfig.setSelect_Homegrp_Homehub_Device_Id(homehubDeviceId);
                mAppConfig.setsSelect_Homegrp_Homehub_Device_Key(homehubDeviceKey);
                mAppConfig.setsSelect_Homegrp_Homehub_Conn_State(homehubConnState);
                mAppConfig.setsSelect_Homegrp_Homehub_Dongle_State(homehubDongleState);
                mAppConfig.setsSelect_Servicehub_App_Id(servicehubApplicationId);
                mAppConfig.setsSelect_Homegrp_Homehub_Dongle_Online_Last_Datetime(
                        deviceOnlineLastDatetime);

                if (mUtil.str2int(invitationsCount) > 0) {
                    Intent intent = new Intent(mActivity, InvitationList.class);
                    mUtil.callActivityForResultNoAnim(mActivity, intent,
                            Constants.ACT_INVITATION_LIST);
                    return;
                }

                setFinish();
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String errorCode = mUtil.null2string(joResult.get(Constants.HTTP_err_code));
                String errorMsg = mUtil.null2string(joResult.get(Constants.HTTP_err_msg));

                if ("401".equals(errorCode)) {
                    mUtil.getView(mActivity, R.id.llRoot).setVisibility(View.VISIBLE);
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, errorMsg);
                } else if ("401-101".equals(errorCode)) {
                    mUtil.getView(mActivity, R.id.llRoot).setVisibility(View.VISIBLE);
                    mCustomDialog.msgAlert(mActivity, Constants.MSG828, mId,
                            R.string.MSG_TITLE_001);
                } else if ("401-103".equals(errorCode)) {
                    String nickname = mUtil.null2string(joResult.get(Constants.HTTP_nickname));
                    Intent intent = new Intent(mActivity, LoginNewDevice.class);
                    intent.putExtra(Constants.EXTRA_EMAIL_ID, mId);
                    intent.putExtra(Constants.EXTRA_NICKNAME, nickname);
                    mUtil.callActivityForResult(mActivity, intent, Constants.ACT_LOGIN_NEW_DEVICE);
                } else {
                    mUtil.getView(mActivity, R.id.llRoot).setVisibility(View.VISIBLE);
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, errorMsg);
                }
            }
        } 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() {

        finishhandler.sendEmptyMessageDelayed(0, FINISH_INTERVAL); // ms,
    }

    private Handler finishhandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {

            if (!mAppConfig.getMain()) {
                setFinishLoading();
            } else {
                finish();
            }
            return false;
        }
    });

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

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