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

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

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.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
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.c_interface.Main_Interface;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
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.R;
import com.ntels.kneet.v3.view.dialog.CustomDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class Things_Device_Del_01 extends CustomActivity 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_D_DEVICES_DEVICE_ID_COMMANDS_STATUS = 1;

    /*공통*/
    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      bReloadFinishFlag = false;
    private String       sDEVICE_NAME      = "";
    private String       sGROUP_DEVICE     = "";
    private String       sCOMPANY_NAME     = "";
    private String       sDEVICE_DESC      = "";
    private String       sDEVICE_DESC1     = "";
    private int          iDEVICE_IMAGE     = 0;
    private int          iDEVICE_IMAGE1    = 0;

    @Override public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

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

        View viewToLoad = LayoutInflater.from(act).inflate(R.layout.things_device_del_01, 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);
            sDEVICE_NAME = intent.getStringExtra(Constants.EXTRA_DEVICE_NAME);
            sGROUP_DEVICE = intent.getStringExtra(Constants.EXTRA_GROUP_DEVICE);
            sCOMPANY_NAME = intent.getStringExtra(Constants.EXTRA_COMPANY_NAME);
            sDEVICE_DESC = intent.getStringExtra(Constants.EXTRA_DEVICE_DESC);
            sDEVICE_DESC1 = intent.getStringExtra(Constants.EXTRA_DEVICE_DESC1);
            iDEVICE_IMAGE = intent.getIntExtra(Constants.EXTRA_DEVICE_IMAGE, 0);
            iDEVICE_IMAGE1 = intent.getIntExtra(Constants.EXTRA_DEVICE_IMAGE1, 0);
        }

        setDisp();
    }

    private void setDisp() {

        util.getView(act, R.id.llPageRoot).setVisibility(View.VISIBLE);

        util.getView(act, R.id.llStart).setVisibility(View.VISIBLE);
        util.getView(act, R.id.llReStart).setVisibility(View.GONE);
        util.getView(act, R.id.llBtn1).setOnClickListener(this);
        util.getView(act, R.id.llBtn2).setOnClickListener(this);
        util.getView(act, R.id.btnReStart).setOnClickListener(this);

        util.getTextView(act, R.id.tvDeviceName).setText(sDEVICE_NAME);
        util.getTextView(act, R.id.tvDeviceGroup).setText(sGROUP_DEVICE);
        util.getTextView(act, R.id.tvDeviceDesc).setText(sDEVICE_DESC);
        util.setImage(act, iDEVICE_IMAGE, util.getImageView(act, R.id.ivIconDevice));
    }

    @Override public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    @Override public void onClick(View v) {

        switch (v.getId()) {
            case R.id.llBtn2:
                onBackPressed();
                break;
            case R.id.llBtn1:
                if ( appConfig.getSelect_Homegrp_Homehub_Online_State().equals("ON") ) {
                    // 인클루젼/익스클루전 시작 시간 기록후 재 시작시 63초 이후 여부 확인후 잠시후 다시 시도하세요 토스트 뿌려준다
                    String sTime = util.getPreferences(act, Constants.EXTRA_THINGS_ADD_REMOVE_TIME);
                    if (!sTime.equals("")){
                        if ( util.str2long(util.getRealTime1()) < util.str2long(util.stringDateAddTime(sTime, 80000)) ) {
                            util.setShowToast(act, util.getString(act, R.string.MSG903), Toast.LENGTH_SHORT);
                            return;
                        }
                    }
                    util.getView(act, R.id.llBtn1).setEnabled(false);
                    util.getView(act, R.id.btnReStart).setEnabled(false);
                    util.setPreferences(act, Constants.EXTRA_THINGS_ADD_REMOVE_TIME, util.getRealTime1());
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_D_DEVICES_DEVICE_ID_COMMANDS_STATUS), 10);
                } else {
                    util.setShowToast(act, util.getString(act, R.string.MSG866), Toast.LENGTH_SHORT);
                    return;
                }
                break;
            case R.id.btnReStart:
                if ( appConfig.getSelect_Homegrp_Homehub_Online_State().equals("ON") ) {
                    util.getView(act, R.id.llBtn1).setEnabled(false);
                    util.getView(act, R.id.btnReStart).setEnabled(false);
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_D_DEVICES_DEVICE_ID_COMMANDS_STATUS), 10);
                } else {
                    util.setShowToast(act, util.getString(act, R.string.MSG866), Toast.LENGTH_SHORT);
                    return;
                }
                break;
            default:
                break;
        }
    }
    @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;
        }
    }
    /**
     * <PRE>
     * 1. MethodName: onBackPressed
     * 2. ClassName :
     * 3. Comment   : 뒤로가기 버튼
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onBackPressed() {

        intent = new Intent();
        act.setResult(RESULT_CANCELED, intent);
        finish();
        return;
    }

    /**
     * <PRE>
     * 1. MethodName: onResume
     * 2. ClassName :
     * 3. Comment   : onResume
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onResume() {

        super.onResume();

        // if (!GreenBilllab.getIntro()) {
        // if (Main.reLoginCheck()) {
        // 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_D_DEVICES_DEVICE_ID_COMMANDS_STATUS:
                    //dialog_show();
                    send_D_devices_device_id_commands_status();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

    /**
     * <PRE>
     * 1. MethodName: send_D_devices_device_id_commands_status
     * 2. ClassName :
     * 3. Comment   : [Send][DELETE]하위 장치 삭제 제어 명령 실행 (익스클루전)(하위 장치 삭제 가능 상태로 제어 명령을 실행한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void send_D_devices_device_id_commands_status() {

        try {
            HttpSend httpSend;

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

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

                    result_D_devices_device_id_commands_status(result);
                }
            });
            httpSend.D_devices_device_id_commands_status(appConfig.getSelect_Homegrp_Homehub_Device_Id());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * <PRE>
     * 1. MethodName: result_D_devices_device_id_commands_status
     * 2. ClassName :
     * 3. Comment   : [Result][DELETE]하위 장치 삭제 제어 명령 실행 (익스클루전)(하위 장치 삭제 가능 상태로 제어 명령을 실행한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void result_D_devices_device_id_commands_status(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                String sHTTP_command_id = util.null2string(joResult.get(Constants.HTTP_command_id));

                util.getView(act, R.id.llPageRoot).setVisibility(View.INVISIBLE);
                intent = new Intent(act, Things_Device_Del_02.class);
                intent.putExtra(Constants.EXTRA_DEVICE_NAME, sDEVICE_NAME);
                intent.putExtra(Constants.EXTRA_GROUP_DEVICE, sGROUP_DEVICE);
                intent.putExtra(Constants.EXTRA_COMPANY_NAME, sCOMPANY_NAME);
                intent.putExtra(Constants.EXTRA_DEVICE_DESC1, sDEVICE_DESC1);
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, iDEVICE_IMAGE1);
                intent.putExtra(Constants.EXTRA_COMMAND_ID, sHTTP_command_id);
                util.callActivityForResultNoAnim(act, intent, Constants.ACT_THINGS_DEVICE_DEL_02);
            } 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);
        }
        try {
            util.getView(act, R.id.llBtn1).setEnabled(true);
            util.getView(act, R.id.btnReStart).setEnabled(true);
        } catch (Exception ex) {

        }
    }

    @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_THINGS_DEVICE_DEL_02:
                    act.setResult(RESULT_OK, data);
                    finish();
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_THINGS_DEVICE_DEL_02:
                    Boolean bFlow_End_Flag = data.getBooleanExtra(Constants.EXTRA_FLOW_END_FLAG, false);
                    Boolean bTimeOut_Flag = data.getBooleanExtra(Constants.EXTRA_TIMEOUT_FLAG, false);
                    if ( bFlow_End_Flag ) {
                        act.setResult(RESULT_CANCELED, data);
                        finish();
                    } else {
                        util.getView(act, R.id.llPageRoot).setVisibility(View.VISIBLE);
                        if ( bTimeOut_Flag ) {
                            util.getView(act, R.id.llBtn1).setVisibility(View.GONE);
                            util.getView(act, R.id.llStart).setVisibility(View.GONE);
                            util.getView(act, R.id.llReStart).setVisibility(View.VISIBLE);
                        } else {
                            util.getView(act, R.id.llBtn1).setVisibility(View.VISIBLE);
                            util.getView(act, R.id.llStart).setVisibility(View.VISIBLE);
                            util.getView(act, R.id.llReStart).setVisibility(View.GONE);
                        }
                    }
                    break;
            }
        }
    }
}

