/*
 * 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.db.DatabaseOpenHelper;
import com.ntels.onecable.common.db.SqlManager;
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.CustomActivity;
import com.ntels.onecable.view.dialog.CustomDialog;
import com.ntels.onecable.view.invitation.InvitationList;

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

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

    private static final int MSG_COM_P_MEMBER_NEW_MOBILE_DEVICE = 1;
    Intent intent;
    Handler mComHandler = new Handler(new IncomingHandlerCallBack());
    private SqlManager mSqlManager = new SqlManager();
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Util mUtil = new Util();
    private CustomDialog customDialog = new CustomDialog();
    private int type = 0;
    private String emailId = "";
    private String key = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mActivity = LoginNewDevice.this;
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

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

        if (null != getIntent()) {
            Intent intent = getIntent();
            emailId = intent.getStringExtra(Constants.EXTRA_EMAIL_ID);
        }

        mUtil.getTextView(mActivity, R.id.tvEmail).setText(emailId);
        mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llBtn1:
                if (!checkFormValid()) {
                    return;
                }
                view.setEnabled(false);
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(
                        MSG_COM_P_MEMBER_NEW_MOBILE_DEVICE), Constants.HANDLER_DELAY_MILLIS);
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_CANCELED, new Intent());
        finish();
    }

    @Override
    public void setAnimFinish(String val) {

        super.setAnimFinish(val);
    }

    @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.MSG807:
                if (btnResult == 1) {
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(type),
                            Constants.HANDLER_DELAY_MILLIS);
                } else {
                    mActivity.finish();
                }
                break;
            case Constants.MSG840:
                mActivity.finish();
                break;
            case Constants.MSG820:
                if (btnResult == 1) {
                    Intent intent =
                            new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    intent.addCategory(Intent.CATEGORY_DEFAULT);
                    mUtil.callActivityForResult(mActivity, intent, Constants.ACT_GOOGLE_CHECK);
                } else {
                    setFinish();
                }
                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_INVITATION_LIST:
                    intent = new Intent();
                    intent.putExtra(Constants.EXTRA_RELOAD_FLAG, true);
                    mActivity.setResult(RESULT_OK, intent);
                    finish();
                    break;
                default:
                    break;
            }
        } else {
            if (mAppConfig.getGoErr()) {
                mAppConfig.setGoErr(true);
                setResult(RESULT_CANCELED, new Intent());
                finish();
            } else {
                switch (requestCode) {
                    case Constants.ACT_INVITATION_LIST:
                        intent = new Intent();
                        intent.putExtra(Constants.EXTRA_RELOAD_FLAG, false);
                        mActivity.setResult(RESULT_OK, intent);
                        finish();
                        break;
                    default:
                        break;
                }
            }
        }
    }

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

        Boolean isCheck = true;
        key = mUtil.getEditTextVal(mActivity, R.id.edtKey);
        if (key.trim().length() < 1) {
            isCheck = false;
            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG837), Toast.LENGTH_SHORT);
            return isCheck;
        }

        return isCheck;
    }

    /**
     * <pre>
     * 단말(장치) 인증(새로운 단말로 로그인 시 단말(장치) 인증 번호를 확인하고,
     * 단말(장치)을 등록 처리 요청한다.
     * (기존 단말(장치)을 대체할 경우의 처리도 포함))
     * </pre>
     */
    private void sendPostMemberNewMobileDevice() {

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

                    resultPostMemberNewMobileDevice(result);
                }
            });

            httpSend.P_member_new_mobile_device(key, emailId, mAppConfig.getService_Id(),
                    Constants.OS_TYPE, mAppConfig.getUuid(), mAppConfig.getPush_Token(),
                    mUtil.getPhoneName(), mUtil.getHostName());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 단말(장치) 인증(새로운 단말로 로그인 시 단말(장치) 인증 번호를 확인하고,
     * 단말(장치)을 등록 처리 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultPostMemberNewMobileDevice(Response result) {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                //회원 번호
                String memberId = mUtil.null2string(joResult.get(Constants.KEY_MEMBER_ID));
                mAppConfig.setLoginMemberId(memberId);
                //이메일 ID
                String emailId = mUtil.null2string(joResult.get(Constants.KEY_EMAIL_ID));
                mAppConfig.setLoginId(emailId);
                if ("Y".equals(tempPasswordYn)) {
                    String pass = "";
                    mAppConfig.setLogin_Pass(pass);
                } else {
                    mAppConfig.setLogin_Pass("");
                }
                Boolean isAutoLogin = false;
                mAppConfig.setIsAutoLogin(isAutoLogin);
                mAppConfig.setIsLogin(true);

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

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

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

                String pushTypeModeChgYn = mUtil.null2string(joResult.get(Constants.KEY_PUSH_TYPE_MODE_CHG_YN));
                mAppConfig.setPush_Type_Mode_Chg_Yn(pushTypeModeChgYn);
                String pushTypePrsncChgYn = mUtil.null2string(joResult.get(Constants.KEY_PUSH_TYPE_PRSNC_CHG_YN));
                mAppConfig.setPush_Type_Prsnc_Chg_Yn(pushTypePrsncChgYn);
                mAppConfig.setInvitations_Count(invitationCount);
                mAppConfig.setCtrtGroupId(homegrpId);
//                mAppConfig.setSelect_Homegrp_Icon(homegrpImageFileName);
                mAppConfig.setCtrtGroupName(homegrpName);
                mAppConfig.setCtrtGroupGradeCode(gradeCode);
                mAppConfig.setSelectHomehubDeviceId(homehubDeviceId);
                mAppConfig.setSelectHomehubDeviceKey(homehubDeviceKey);
//                mAppConfig.setsSelect_Homegrp_Homehub_Conn_State(homehubConnState);
                mAppConfig.getDevicesList(homehubDeviceId).put(Constants.KEY_DEVICE_CONN, homehubConnState);
//                mAppConfig.setsSelect_Homegrp_Homehub_Dongle_State(homehubDongleState);
                mAppConfig.getDevicesList(homehubDeviceId).put(Constants.KEY_DEVICE_ONLINE, homehubDongleState);
                mAppConfig.setSelectServicehubAppId(servicehubApplicationId);
                mAppConfig.setsSelect_CtrtGroup_Homehub_Dongle_Online_Last_Datetime(
                        deviceOnlineLastDatetime);

                if (mUtil.str2int(invitationCount) > 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.KEY_ERR_CODE));
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                if ("401".equals(resultCode)) {
                    customDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else if ("401-106".equals(resultCode)) {
                    customDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    customDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                }
            }
        } catch (JSONException ex) {
            ex.printStackTrace();
            customDialog.msgAlert(mActivity, Constants.MSG807);
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(mActivity, Constants.MSG807);
        }
        try {
            mUtil.getView(mActivity, R.id.llBtn1).setEnabled(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Activity 종료.
     */
    private void setFinish() {

        intent = new Intent();
        intent.putExtra(Constants.EXTRA_RELOAD_FLAG, false);
        mActivity.setResult(RESULT_OK, intent);
        finish();
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            type = msg.what;
            switch (msg.what) {
                case MSG_COM_P_MEMBER_NEW_MOBILE_DEVICE:
                    sendPostMemberNewMobileDevice();
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}
