/*
 * 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.CustomActionBarActivity;
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 CustomActionBarActivity implements View.OnClickListener,
        CustomDialog.OnMsgAlterToResult {

    private static final int MSG_COM_P_MEMBER_NEW_MOBILE_DEVICE = 1;
    Intent intent;
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    private SqlManager mSqlManager = new SqlManager();
    private Activity act;
    private AppConfig appConfig;
    private Util util = 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);

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

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

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

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

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llBtn1:
                if (!checkFormValid()) {
                    return;
                }
                view.setEnabled(false);
                comHandler.sendMessageDelayed(comHandler.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:
                util.callApp_Start(act, "LOGOUT");
                break;
            case Constants.MSG997:
                util.callApp_Start(act, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(type),
                            Constants.HANDLER_DELAY_MILLIS);
                } else {
                    act.finish();
                }
                break;
            case Constants.MSG840:
                act.finish();
                break;
            case Constants.MSG820:
                if (btnResult == 1) {
                    Intent intent =
                            new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    intent.addCategory(Intent.CATEGORY_DEFAULT);
                    util.callActivityForResult(act, 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);
                    act.setResult(RESULT_OK, intent);
                    finish();
                    break;
                default:
                    break;
            }
        } else {
            if (appConfig.getGoErr()) {
                appConfig.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);
                        act.setResult(RESULT_OK, intent);
                        finish();
                        break;
                    default:
                        break;
                }
            }
        }
    }

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

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

        return isCheck;
    }

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

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

                    resultPostMemberNewMobileDevice(result);
                }
            });

            httpSend.P_member_new_mobile_device(key, emailId, appConfig.getService_Id(),
                    Constants.OS_TYPE, appConfig.getUuid(), appConfig.getPush_Token(),
                    util.getPhoneName(), util.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_IMAGE_FILE_NAME)) {
                    imageFileName = util.null2string(joResult.get(Constants.KEY_IMAGE_FILE_NAME));
                    appConfig.setMy_Image_Url(imageFileName);
                }
                //회원명
                String nickname = "";
                if (joResult.has(Constants.KEY_NICKNAME)) {
                    nickname = util.null2string(joResult.get(Constants.KEY_NICKNAME));
                    appConfig.setNickname(nickname);
                }

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

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

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

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

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

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

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

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

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

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

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

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

                //회원 번호
                String memberId = util.null2string(joResult.get(Constants.KEY_MEMBER_ID));
                appConfig.setLogin_Member_Id(memberId);
                //이메일 ID
                String emailId = util.null2string(joResult.get(Constants.KEY_EMAIL_ID));
                appConfig.setLogin_Id(emailId);
                if ("Y".equals(tempPasswordYn)) {
                    String pass = "";
                    appConfig.setLogin_Pass(pass);
                } else {
                    appConfig.setLogin_Pass("");
                }
                Boolean isAutoLogin = false;
                appConfig.setAutoLogin(isAutoLogin);
                appConfig.setLogin(true);

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

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

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

                String pushTypeModeChgYn = util.null2string(joResult.get(
                        Constants.KEY_PUSH_TYPE_MODE_CHG_YN));
                appConfig.setPush_Type_Mode_Chg_Yn(pushTypeModeChgYn);
                String pushTypePrsncChgYn = util.null2string(joResult.get(
                        Constants.KEY_PUSH_TYPE_PRSNC_CHG_YN));
                appConfig.setPush_Type_Prsnc_Chg_Yn(pushTypePrsncChgYn);
                appConfig.setInvitations_Count(invitationCount);
                appConfig.setCtrtGroupId(homegrpId);
                appConfig.setSelect_Homegrp_Icon(homegrpImageFileName);
                appConfig.setSelect_Homegrp_Name(homegrpName);
                appConfig.setSelect_Homegrp_Grade_Code(gradeCode);
                appConfig.setSelect_Homegrp_Homehub_Device_Id(homehubDeviceId);
                appConfig.setsSelect_Homegrp_Homehub_Device_Key(homehubDeviceKey);
                appConfig.setsSelect_Homegrp_Homehub_Conn_State(homehubConnState);
                appConfig.setsSelect_Homegrp_Homehub_Dongle_State(homehubDongleState);
                appConfig.setsSelect_Servicehub_App_Id(servicehubApplicationId);
                appConfig.setsSelect_Homegrp_Homehub_Dongle_Online_Last_Datetime(
                        deviceOnlineLastDatetime);

                if (util.str2int(invitationCount) > 0) {
                    Intent intent = new Intent(act, InvitationList.class);
                    util.callActivityForResultNoAnim(act, intent, Constants.ACT_INVITATION_LIST);
                    return;
                }

                setFinish();
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String errorCode = util.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String errorMsg = util.null2string(joResult.get(Constants.KEY_ERR_MSG));

                if ("401".equals(errorCode)) {
                    customDialog.msgAlert(act, Constants.MSG998, errorMsg);
                } else if ("401-106".equals(errorCode)) {
                    customDialog.msgAlert(act, Constants.MSG997, errorMsg);
                } else {

                    customDialog.msgAlert(act, Constants.MSG000, errorMsg);
                }
            }
        } catch (JSONException ex) {
            ex.printStackTrace();
            customDialog.msgAlert(act, Constants.MSG807);
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(act, Constants.MSG807);
        }
        try {
            util.getView(act, R.id.llBtn1).setEnabled(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        intent = new Intent();
        intent.putExtra(Constants.EXTRA_RELOAD_FLAG, false);
        act.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;
        }
    }
}
