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

package com.ntels.kneet.v3.view.main_more;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
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.Main_Interface;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
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 org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

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

    /*툴바 관련*/
    private Toolbar toolbar;

    /*통신 관련*/
    private              ArrayList<HashMap<String, Object>> alTotalList                          = new ArrayList<HashMap<String, Object>>();
    private              int                                iType                                = 0;
    private static final int                                MSG_COM_P_MODES_MODE_ID_CURRENT_MODE = 1;
    private static final int                                MSG_COM_G_MODES_MODE_ID_STATUS       = 2;

    /*공통*/
    private Activity       act;
    private AppConfig      appConfig;
    private Main_Interface mCallback;
    private Intent         intent;
    private              Util                               util                        = new Util();
    private              CustomDialog                       customDialog                = new CustomDialog();
    private              String                             sCallType                   = "";
    private              SQLManager                         sqlManager                  = new SQLManager();
    private              Boolean                            bAutoLogin                  = false;
    private              Boolean                            bSaveId                     = false;
    private              String                             sFileName                   = "";
    private              String                             sHTTP_push_type_mode_chg_yn = "";
    private              String                             sHTTP_push_type_rule_exc_yn = "";
    private              String                             sMODE_ID                    = "";
    private              String                             sBASIC_MODE_CODE            = "";
    private              String                             sMODE_ICON                  = "";
    private              String                             sMODE_ICON1                 = "";
    private              String                             sMODE_NAME                  = "";
    private              String                             sMODE_TITLE                 = "";
    private              String                             sMODE_TITLE1                = "";
    private              String                             sMODE_DEL_YN                = "";
    private              String                             sHOMEGRP_RULE_ID            = "";
    private              String                             sMODE_CHANGE_STARET_TIME    = "";
    private              ArrayList<HashMap<String, Object>> alList_Actions              = new ArrayList<HashMap<String, Object>>();
    private              int                                iAlram_Type                 = 0;
    private static final int                                ALRAM_MODE_ON               = 1;
    private static final int                                ALRAM_MODE_OFF              = 2;
    private static final int                                ALRAM_RULE_ON               = 3;
    private static final int                                ALRAM_RULE_OFF              = 4;

    private ScheduledFuture scheduledFuture;
    private Boolean bPollingPause  = false;
    private Boolean bPollingCancel = false;
    private Boolean bActStop       = false;
    Boolean bReload_Flag = false;

    @Override public void onStop() {

        super.onStop();
        Dlog.v("onStop()");
        bPollingPause = true;
        bActStop = true;
    }
    @Override public void onPause() {

        super.onPause();
        Dlog.v("onPause()");
        bPollingPause = true;
        bActStop = true;
    }

    @Override public void onResume() {

        super.onResume();
        Dlog.v("onResume()");
        bPollingPause = false;
        bActStop = false;
    }

    @Override public void onDestroy() {

        super.onDestroy();
        Dlog.v("onDestroy()");
        if ( scheduledFuture != null ) {
            scheduledFuture.cancel(false);
            bPollingPause = true;
        }
    }
    /**
     * <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 = Homemode.this;
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

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

        if ( savedInstanceState != null ) {
            // sTitle =
            // savedInstanceState.getString(Constants.EXTRA_SPINNER_TITLE);
            // aList1 =
            // savedInstanceState.getStringArrayList(Constants.EXTRA_SPINNER_LIST1);
            // aList2 =
            // savedInstanceState.getStringArrayList(Constants.EXTRA_SPINNER_LIST2);
            // // 0: 세로 한개 선택, 1: 가로 한개선택
            // iType = savedInstanceState.getInt(Constants.EXTRA_SPINNER_TYPE,
            // 0);
            // sBtn1 =
            // savedInstanceState.getString(Constants.EXTRA_SPINNER_BTN1);
            // sBtn2 =
            // savedInstanceState.getString(Constants.EXTRA_SPINNER_BTN2);
            // iPosition =
            // savedInstanceState.getInt(Constants.EXTRA_SPINNER_POSITION, 0);
        } else {
            Intent intent = getIntent();
            //            sCallType = intent.getStringExtra(Constants.EXTRA_CALL_TYPE);
            sMODE_ID = intent.getStringExtra(Constants.EXTRA_MODE_ID);
            sBASIC_MODE_CODE = intent.getStringExtra(Constants.EXTRA_BASIC_MODE_CODE);
            sMODE_ICON = intent.getStringExtra(Constants.EXTRA_MODE_ICON);
            sMODE_ICON1 = intent.getStringExtra(Constants.EXTRA_MODE_ICON1);
            sMODE_NAME = intent.getStringExtra(Constants.EXTRA_MODE_NAME);
            sMODE_DEL_YN = intent.getStringExtra(Constants.EXTRA_MODE_DEL_YN);
            sHOMEGRP_RULE_ID = intent.getStringExtra(Constants.EXTRA_HOMEGRP_RULE_ID);
        }

        setDisp();
    }

    private void setDisp() {

        util.getView(act, R.id.btnModeChange).setOnClickListener(this);
        util.getView(act, R.id.btnModeSetup).setOnClickListener(this);
        util.getView(act, R.id.btnClose).setOnClickListener(this);

        util.setImage(act, sMODE_ICON, util.getImageView(act, R.id.ivModeIcon));
        Dlog.v(sMODE_ID, sMODE_ID);
        if ( sBASIC_MODE_CODE.equals("HOME") ) {
            util.getTextView(act, R.id.tvTitle).setText(util.getString(act, R.string.layout_mode_detail_03));
            util.getTextView(act, R.id.tvTitle1).setText(util.getString(act, R.string.layout_mode_detail_04));
        } else if ( sBASIC_MODE_CODE.equals("AWAY") ) {
            util.getTextView(act, R.id.tvTitle).setText(util.getString(act, R.string.layout_mode_detail_05));
            util.getTextView(act, R.id.tvTitle1).setText(util.getString(act, R.string.layout_mode_detail_06));
        } else if ( sBASIC_MODE_CODE.equals("MORNING") ) {
            util.getTextView(act, R.id.tvTitle).setText(util.getString(act, R.string.layout_mode_detail_07));
            util.getTextView(act, R.id.tvTitle1).setText(util.getString(act, R.string.layout_mode_detail_08));
        } else if ( sBASIC_MODE_CODE.equals("NIGHT") ) {
            util.getTextView(act, R.id.tvTitle).setText(util.getString(act, R.string.layout_mode_detail_09));
            util.getTextView(act, R.id.tvTitle1).setText(util.getString(act, R.string.layout_mode_detail_10));
        }

        util.getButton(act, R.id.btnModeChange).setText(sMODE_NAME);

        util.getView(act, R.id.btnModeSetup).setEnabled(true);
        if ( appConfig.getSelect_Homegrp_Grade_Code().equals("MAS") ) {
            util.getTextView(act, R.id.tvDesc).setVisibility(View.INVISIBLE);
            if ( sHOMEGRP_RULE_ID.equals("") ) {
                util.getTextView(act, R.id.tvDesc).setVisibility(View.VISIBLE);
                util.getTextView(act, R.id.tvDesc).setText(util.getString(act, R.string.layout_mode_detail_01));
            } else if ( !sMODE_DEL_YN.equals("0") ) {
                util.getTextView(act, R.id.tvDesc).setVisibility(View.VISIBLE);
                util.getTextView(act, R.id.tvDesc).setText(util.getString(act, R.string.layout_mode_detail_02));
            }
        } else {
            util.getTextView(act, R.id.tvDesc).setVisibility(View.INVISIBLE);
            util.getView(act, R.id.btnModeSetup).setVisibility(View.INVISIBLE);
        }
    }

    @Override public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    @Override public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btnModeSetup:
                util.callBtnGoogleAnalytics(act, "Set_Mode", sMODE_NAME);
                intent = new Intent(act, Homemode_Edit.class);
                intent.putExtra(Constants.EXTRA_MODE_ID, sMODE_ID);
                intent.putExtra(Constants.EXTRA_MODE_ICON, sMODE_ICON);
                intent.putExtra(Constants.EXTRA_MODE_ICON1, sMODE_ICON1);
                intent.putExtra(Constants.EXTRA_MODE_NAME, sMODE_NAME);
                intent.putExtra(Constants.EXTRA_MODE_DEL_YN, sMODE_DEL_YN);
                intent.putExtra(Constants.EXTRA_HOMEGRP_RULE_ID, sHOMEGRP_RULE_ID);
                util.callActivityForResultNoAnim(act, intent, Constants.ACT_HOMEMODE_EDIT);
                break;
            case R.id.btnClose:
                onBackPressed();
                break;
            case R.id.btnModeChange:
                if ( appConfig.getSelect_Homegrp_Homehub_Online_State().equals("ON") ) {
                    util.callBtnGoogleAnalytics(act, "Chage_Mode", sMODE_NAME);
                    util.getView(act, R.id.progressLoading).setVisibility(View.VISIBLE);
                    util.getView(act, R.id.btnModeChange).setVisibility(View.INVISIBLE);
                    util.getView(act, R.id.ivSucess).setVisibility(View.INVISIBLE);
                    util.setVibrator(100);
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_P_MODES_MODE_ID_CURRENT_MODE), 10);
                } else {
                    setModePollingStopFinish();
                }
                break;
            default:
                break;
        }
    }

    private void setModePolling() {

        Dlog.v("Mode setModePolling");
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

        scheduledFuture = scheduler.scheduleAtFixedRate(runnable, 3, 3, TimeUnit.SECONDS);
    }

    Runnable runnable = new Runnable() {
        public void run() {

            Dlog.v("Mode bPollingCancel", bPollingCancel);
            Dlog.v("Mode bPollingPause", bPollingPause);

            if ( bPollingCancel ) {
                scheduledFuture.cancel(false);
            }
            if ( !bPollingPause ) {
                Dlog.v("Mode setModePolling");
                if ( appConfig.getSelect_Homegrp_Homehub_Online_State().equals("ON") ) {
                    //                    Dlog.v("77777777");
                    send_G_modes_mode_id_status();
                } else {
                    //                    Dlog.v("99999999");
                    setModePollingStopFinish();
                }
            }
        }
    };

    private void setModePollingStopFinish() {

        if ( scheduledFuture != null ) {
            scheduledFuture.cancel(false);
        }
        util.setShowToast(act, util.getString(act, R.string.MSG866), Toast.LENGTH_SHORT);
        onBackPressed();
    }

    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_MODES_MODE_ID_CURRENT_MODE:
                    send_P_modes_mode_id_current_mode();
                    break;
                case MSG_COM_G_MODES_MODE_ID_STATUS:
                    //dialog_show();
                    send_G_modes_mode_id_status();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

    /**
     * <PRE>
     * 1. MethodName: send_G_modes_mode_id_status
     * 2. ClassName :
     * 3. Comment   : [Send][GET]홈모드 변경 결과 조회(현재 홈모드 변경으로 장치를 제어한 결과를 조회한다.20.9)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void send_G_modes_mode_id_status() {

        try {
            HttpSend httpSend;

            //            httpSend = new HttpSend(act, !swipeRefreshLayout.isRefreshing());
            httpSend = new HttpSend(act, false);

            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override public void resultResponse(Response result) {

                    result_G_modes_mode_id_status(result);
                }
            });

            bPollingPause = true;
            httpSend.G_modes_mode_id_status(sMODE_ID);
        } catch (Exception ex) {
            ex.printStackTrace();
            bPollingPause = bActStop;
        }
    }

    /**
     * <PRE>
     * 1. MethodName: result_G_modes_mode_id_status
     * 2. ClassName :
     * 3. Comment   : [Result][GET]홈모드 변경 결과 조회(현재 홈모드 변경으로 장치를 제어한 결과를 조회한다.20.9)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void result_G_modes_mode_id_status(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                String sHTTP_status = util.null2string(joResult.get(Constants.HTTP_status));
                Boolean bEndCheck = false;
                if ( !sMODE_CHANGE_STARET_TIME.equals("") ) {
                    if ( util.str2long(util.getRealTime1()) > util.str2long(util.stringDateAddTime(sMODE_CHANGE_STARET_TIME, 10000)) ) {
                        bEndCheck = true;
                    }
                } else {
                    bEndCheck = true;
                }
                if ( sHTTP_status.equals("TRUE") ) {
                    bEndCheck = true;
                }
                if ( bEndCheck ) {
                    sMODE_CHANGE_STARET_TIME = "";
                    if ( scheduledFuture != null ) {
                        scheduledFuture.cancel(false);
                    }
                    util.getView(act, R.id.btnModeSetup).setEnabled(true);
                    util.getImageView(act, R.id.ivModeIcon).setVisibility(View.INVISIBLE);
                    util.getTextView(act, R.id.tvTitle).setText(sMODE_NAME + util.getString(act, R.string.layout_mode_detail_12));
                    util.getTextView(act, R.id.tvTitle1).setText("");
                    util.getTextView(act, R.id.tvTitle1).setVisibility(View.INVISIBLE);
                    util.getView(act, R.id.progressLoading).setVisibility(View.INVISIBLE);
                    util.getView(act, R.id.btnModeChange).setVisibility(View.INVISIBLE);
                    util.getView(act, R.id.ivSucess).setVisibility(View.VISIBLE);
                    bReload_Flag = true;
                }
            } 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") ) {
                    if ( scheduledFuture != null ) {
                        scheduledFuture.cancel(false);
                    }
                    customDialog.MsgAlert(act, Constants.MSG998, sERR_MSG);
                } else if ( sERR_CODE.equals("401-106") ) {
                    if ( scheduledFuture != null ) {
                        scheduledFuture.cancel(false);
                    }
                    customDialog.MsgAlert(act, Constants.MSG997, sERR_MSG);
                } else {
                    customDialog.MsgAlert(act, Constants.MSG000, sERR_MSG);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.MsgAlert(act, Constants.MSG807);
        }
        bPollingPause = bActStop;
    }

    private void send_P_modes_mode_id_current_mode() {

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

                    result_P_modes_mode_id_current_mode(result);
                }
            });

            if ( scheduledFuture != null ) {
                scheduledFuture.cancel(false);
            }
            //공통 변수 입력
            httpSend.P_modes_mode_id_current_mode(sMODE_ID);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void result_P_modes_mode_id_current_mode(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                sMODE_CHANGE_STARET_TIME = util.getRealTime1();
                util.getView(act, R.id.btnModeSetup).setEnabled(false);
                util.getImageView(act, R.id.ivModeIcon).setVisibility(View.INVISIBLE);
                util.getTextView(act, R.id.tvTitle).setText(sMODE_NAME + util.getString(act, R.string.layout_mode_detail_11));
                util.getTextView(act, R.id.tvTitle1).setText("");
                util.getTextView(act, R.id.tvTitle1).setVisibility(View.INVISIBLE);
                util.getView(act, R.id.progressLoading).setVisibility(View.VISIBLE);
                util.getView(act, R.id.btnModeChange).setVisibility(View.INVISIBLE);
                util.getView(act, R.id.ivSucess).setVisibility(View.INVISIBLE);
                bPollingPause = bActStop;
                setModePolling();
            } 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 (Exception ex) {
            ex.printStackTrace();
            customDialog.MsgAlert(act, Constants.MSG807);
        }
    }

    /**
     * <PRE>
     * 1. MethodName: onBackPressed
     * 2. ClassName :
     * 3. Comment   : 뒤로가기 버튼
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onBackPressed() {

        intent = new Intent();
        intent.putExtra(Constants.EXTRA_RELOAD_FLAG, bReload_Flag);
        act.setResult(RESULT_CANCELED, intent);
        finish();
        return;
    }

    @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);
                }
                break;
            default:
                break;
        }
    }

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

        super.onActivityResult(requestCode, resultCode, data);
        if ( resultCode == act.RESULT_OK ) {
            switch (requestCode) {
                case Constants.ACT_HOMEMODE_EDIT:
                    bReload_Flag = true;
                    sMODE_DEL_YN = util.null2string(data.getStringExtra(Constants.EXTRA_MODE_DEL_YN));
                    sHOMEGRP_RULE_ID = util.null2string(data.getStringExtra(Constants.EXTRA_HOMEGRP_RULE_ID));
                    setDisp();
                    break;
            }
        } else {
            switch (requestCode) {
                default:
                    break;
            }
        }
    }
}
