/*
 * 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.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;

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.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 com.ntels.kneet.v3.view.invitation.Invitation_List;

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

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

    private SQLManager sqlManager = new SQLManager();
    private Activity act;
    Intent intent;
    private AppConfig appConfig;
    private Util         util         = new Util();
    private CustomDialog customDialog = new CustomDialog();
    private              int     iType                              = 0;
    private              String  sEMAIL_ID                          = "";
    private              String  sKey                               = "";
    private              String  sPass                              = "";
    private              Boolean bAutoLogin                         = false;
    private              Boolean bSaveId                            = false;
    private static final int     MSG_COM_P_MEMBER_NEW_MOBILE_DEVICE = 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 = Login_New_Device.this;
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

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

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

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

    @Override public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    @Override public void onClick(View v) {

        switch (v.getId()) {
            case R.id.llBtn1:
                if ( !checkFormValid() ) {
                    return;
                }
                v.setEnabled(false);
                ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_P_MEMBER_NEW_MOBILE_DEVICE), 10);
                break;
            default:
                break;
        }
    }

    private Boolean checkFormValid() {

        Boolean bCheck = true;
        sKey = util.getEditTextVal(act, R.id.edtKey);
        if ( sKey.trim().length() < 1 ) {
            bCheck = false;
            util.setShowToast(act, util.getString(act, R.string.MSG837), 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_NEW_MOBILE_DEVICE:
                    send_P_member_new_mobile_device();
                    break;
                default:
                    break;
            }
            return true;
        }
    }

    private void send_P_member_new_mobile_device() {

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

                    result_P_member_new_mobile_device(result);
                }
            });

            httpSend.P_member_new_mobile_device(sKey, sEMAIL_ID, appConfig.getService_Id(), Constants.OS_TYPE, appConfig.getUuid(), appConfig.getPush_Token(), util.getPhoneName(),
                                                util.getHostName());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void result_P_member_new_mobile_device(Response rpResult) {

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

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

                //회원 번호
                String sMEMBER_ID = util.null2string(joResult.get(Constants.HTTP_member_id));
                //이메일 ID
                String sEMAIL_ID = util.null2string(joResult.get(Constants.HTTP_email_id));
                //서비스 ID
                String sSERVICE_ID = util.null2string(joResult.get(Constants.HTTP_service_id));
                //국가 코드 (ex: KR)
                String sCOUNTRY_CODE = util.null2string(joResult.get(Constants.HTTP_country_code));
                //타임존 ID
                String sTIMEZONE_ID = util.null2string(joResult.get(Constants.HTTP_timezone_id));
                //타임존 시간 (ex: +09:00)
                String sTIMEZONE = util.null2string(joResult.get(Constants.HTTP_timezone));
                //언어 코드 (ex: en)
                String sLANG = util.null2string(joResult.get(Constants.HTTP_lang));
                //인증 토큰
                String sAUTH_TOKEN = util.null2string(joResult.get(Constants.HTTP_auth_token));

                //회원이미지 추가
                String sIMAGE_FILE_NAME = "";
                if ( joResult.has(Constants.HTTP_image_file_name) ) {
                    sIMAGE_FILE_NAME = util.null2string(joResult.get(Constants.HTTP_image_file_name));
                    appConfig.setMy_Image_Url(sIMAGE_FILE_NAME);
                }
                //회원명
                String sNICKNAME = "";
                if ( joResult.has(Constants.HTTP_nickname) ) {
                    sNICKNAME = util.null2string(joResult.get(Constants.HTTP_nickname));
                    appConfig.setNickname(sNICKNAME);
                }

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

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

                String sPUSH_TYPE_MODE_CHG_YN = util.null2string(joResult.get(Constants.HTTP_push_type_mode_chg_yn));
                String sPUSH_TYPE_PRSNC_CHG_YN = util.null2string(joResult.get(Constants.HTTP_push_type_prsnc_chg_yn));

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

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

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

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

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

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

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

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

                /*String sHTTP_homehub_online_state = "";
                if ( joResult.has(Constants.HTTP_homehub_online_state) ) {
                    sHTTP_homehub_online_state = util.null2string(joResult.get(Constants.HTTP_homehub_online_state));
                }*/

                appConfig.setLogin_Member_Id(sMEMBER_ID);
                appConfig.setLogin_Id(sEMAIL_ID);
                if ( sHTTP_TEMP_PASSWORD_YN.equals("Y") ) {
                    appConfig.setLogin_Pass(sPass);
                } else {
                    appConfig.setLogin_Pass("");
                }
                appConfig.setAutoLogin(bAutoLogin);
                appConfig.setLogin(true);

                //공통 변수 입력
                appConfig.setAuth_Token(sAUTH_TOKEN);

                //db 입력작업
                SQLiteDatabase db = DatabaseOpenHelper.getInstance(act).getWritableDatabase();
                String sSql = "";
                sSql = "";
                sSql = sqlManager.QryDelLoginInfo();
                db.execSQL(sSql);

                sSql = "";
                sSql = sqlManager.QryInsertLoginInfo(sEMAIL_ID, sAUTH_TOKEN, bSaveId, bAutoLogin, appConfig.getManualNotView(), appConfig.getPush());
                db.execSQL(sSql);
                db.close();

                appConfig.setPush_Type_Mode_Chg_Yn(sPUSH_TYPE_MODE_CHG_YN);
                appConfig.setPush_Type_Prsnc_Chg_Yn(sPUSH_TYPE_PRSNC_CHG_YN);
                appConfig.setInvitations_Count(sHTTP_invitations_count);
                appConfig.setSelect_Homegrp_Id(sHTTP_homegrp_id);
                appConfig.setSelect_Homegrp_Icon(sHTTP_homegrp_image_file_name);
                appConfig.setSelect_Homegrp_Name(sHTTP_homegrp_name);
                appConfig.setSelect_Homegrp_Grade_Code(sHTTP_grade_code);
                appConfig.setSelect_Homegrp_Homehub_Device_Id(sHTTP_homehub_device_id);
                appConfig.setsSelect_Homegrp_Homehub_Conn_State(sHTTP_homehub_conn_state);
                appConfig.setsSelect_Homegrp_Homehub_Dongle_State(sHTTP_homehub_dongle_state);
//                appConfig.setSelect_Homegrp_Homehub_Online_State(sHTTP_homehub_online_state);

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

                setFinish();
            } 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 (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) {

        }
    }

    /**
     * <PRE>
     * 1. MethodName: onBackPressed
     * 2. ClassName :
     * 3. Comment   : onBackPressed
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onBackPressed() {
        setResult(RESULT_CANCELED, new Intent());
        finish();
    }

    @Override protected void onDestroy() {

        super.onDestroy();
    }

    @Override public void setAnimFinish(String sVal) {

        super.setAnimFinish(sVal);
    }

    /**
     * <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.MSG807:
                if ( iBtnResult == 1 ) {
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(iType), 10);
                } else {
                    act.finish();
                }
                break;
            case Constants.MSG840:
                act.finish();
                break;
            case Constants.MSG820:
                if ( iBtnResult == 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;
                }
            }
        }
    }

    private void setFinish() {

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