package kr.co.icontrols.iotplatform;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.amazonaws.mobileconnectors.iot.AWSIotMqttNewMessageCallback;

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

import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

import kr.co.icontrols.iotplatform.DataClass.DeviceInfo;
import kr.co.icontrols.iotplatform.DataClass.UserInfo;
import kr.co.icontrols.iotplatform.Database.DBUtil;
import kr.co.icontrols.iotplatform.Mqtt.MqttController;
import kr.co.icontrols.iotplatform.adapter.MyGroupTabPagerAdapter;
import kr.co.icontrols.iotplatform.utils.CommonUtils;
import kr.co.icontrols.iotplatform.utils.HttpApi;
import kr.co.icontrols.iotplatform.utils.SharedPrefUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static kr.co.icontrols.iotplatform.Database.DatabaseHelper.TABLE_DEVICE_HOME;
import static kr.co.icontrols.iotplatform.Database.DatabaseHelper.TABLE_DEVICE_RANK;
import static kr.co.icontrols.iotplatform.Database.DatabaseHelper.TABLE_SMART_LIGHT;
import static kr.co.icontrols.iotplatform.PopupActivity.POPUP_BUNDLE;
import static kr.co.icontrols.iotplatform.PopupActivity.POPUP_TIME_INDEX;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.DebugLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.DismissConnectDialog;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.ErrorLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.ForceDismissConnectDialog;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.IsRunningProgress;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.WarnLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.displayProgress;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.isRestartAppForBackgroundWaitTime;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.resetBackgroundWaitTime;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.restartApp;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.setBackgroundWaitTime;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.showNotiMsg;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_DEVICE_INFO;
import static kr.co.icontrols.iotplatform.utils.Constants.MQTT_PUBLISH_DELAY_TIME;
import static kr.co.icontrols.iotplatform.utils.Constants.NOTING;
import static kr.co.icontrols.iotplatform.utils.Constants.POWER_OFF;
import static kr.co.icontrols.iotplatform.utils.Constants.POWER_ON;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_CHANGE_JAESIL_TIME;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_INPUT_DEVICE_NAME;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_INPUT_HP;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_UPDATE_DATA;

public class LightDetailActivity extends AppCompatActivity implements View.OnClickListener {

    private String TAG = "LightDetailActivity";

    private boolean isConnectedDevice;
    private boolean isChangeData;

    private DeviceInfo deviceInfo;
    private TextView txtLightName,txtGroupName;
    private Button btnOnOff;
    private ImageButton btnEdit;
    private SeekBar seekBarDimLevel, seekBarColorLevel;
    private LinearLayout layoutModeLife, layoutModeStudy, layoutModeRead;

    private int power = NOTING;
    private int dimming = NOTING;
    private int colorTemp = NOTING;

    private String topicGetP, topicGetS1, topicUpdateP, topicUpdateS1, topicUpdateS2;

    private int powerJaesil = NOTING;
    private int mSelectJaesilTime;  //Minutes
    private String topicJaesilGetP,topicJaesilGetS1,topicJaesilSetP,topicJaesilSetS1;

    private Handler mConnectedHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_light_detail);

        isConnectedDevice = false;
        isChangeData = false;

        deviceInfo = getIntent().getParcelableExtra(EXTRA_DEVICE_INFO);

        topicGetP = String.format(getString(R.string.topic_get_status),deviceInfo.deviceType,deviceInfo.deviceId);
        topicGetS1 = String.format(getString(R.string.topic_response_status),deviceInfo.deviceType,deviceInfo.deviceId);
        topicUpdateP = String.format(getString(R.string.topic_update),deviceInfo.deviceId);
        topicUpdateS1 = String.format(getString(R.string.topic_update_accepted),deviceInfo.deviceId);
        topicUpdateS2 = String.format(getString(R.string.topic_update_delta),deviceInfo.deviceId);

        mSelectJaesilTime = 60;
        topicJaesilGetP = String.format(getString(R.string.topic_get_jaesil_data),deviceInfo.deviceId);
        topicJaesilGetS1 = String.format(getString(R.string.topic_response_get_jaesil_data),deviceInfo.deviceId);
        topicJaesilSetP = String.format(getString(R.string.topic_set_jaesil_data),deviceInfo.deviceId);
        topicJaesilSetS1 = String.format(getString(R.string.topic_response_set_jaesil_data),deviceInfo.deviceId);

        initUI();

        mConnectedHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                WarnLogOutput(TAG, "mConnectedHandler : is mqtt connect ? " + MqttController.getInstance().isConneted());
                if(MqttController.getInstance().isConneted()) {
                    setControllMqtt();
                    getJaesilData();
                } else {
                    mConnectedHandler.sendEmptyMessageDelayed(1,1000);
                }
            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();

        if(isRestartAppForBackgroundWaitTime()) {
            restartApp(this);
            return;
        }

        if(!MqttController.getInstance().isConneted()) {
            mConnectedHandler.sendEmptyMessageDelayed(1,1000);
        } else {
            setControllMqtt();
            getJaesilData();
        }
    }

    @Override
    protected void onPause() {
        if(IsRunningProgress()) {
            ForceDismissConnectDialog();
        }
        MqttController.getInstance().allUnsubscribeToTopics();
        setBackgroundWaitTime();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        resetBackgroundWaitTime();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if(isChangeData) {
            setResult(RESULT_OK);
            finish();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_INPUT_DEVICE_NAME:
                if (resultCode == RESULT_OK) {
                    Bundle b = data.getBundleExtra(POPUP_BUNDLE);
                    if(b != null) {
                        try {
                            String newValue = b.getString(PopupActivity.POPUP_INPUT);
                            if(!newValue.equals(txtLightName.getText().toString())) {
                                changeDeviceName(newValue);
                            }
                        } catch (Exception e) {
                            // Log failure
                            showNotiMsg(LightDetailActivity.this,getString(R.string.snackbar_fail_change_device_name));
                        }
                    } else {
                        showNotiMsg(LightDetailActivity.this,getString(R.string.snackbar_fail_change_device_name));
                    }
                }
                break;
            case RESULT_UPDATE_DATA:
                if(resultCode == RESULT_OK) {
                    for(int i = 0 ; i < UserInfo.devices.size() ; i++) {
                        if(UserInfo.devices.get(i).deviceId.equals(deviceInfo.deviceId)) {
                            if(!UserInfo.devices.get(i).dgroupId.equals(deviceInfo.dgroupId)) {
                                deviceInfo.dgroupName = UserInfo.devices.get(i).dgroupName;
                                deviceInfo.dgroupId = UserInfo.devices.get(i).dgroupId;
                                isChangeData = true;
                            }
                        }
                    }
                    txtGroupName.setText(deviceInfo.dgroupName);
                }
                break;
            case RESULT_CHANGE_JAESIL_TIME:
                if (resultCode == RESULT_OK) {
                    final int selectedTime = data.getIntExtra(POPUP_TIME_INDEX, 60);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            displayProgress(LightDetailActivity.this, "","",2000);
                            changeSetTime(true, power, selectedTime, 0);
                        }
                    },MQTT_PUBLISH_DELAY_TIME+20);
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        /*
        final View fv = v;
        fv.setEnabled(false);
        Timer buttonTimer = new Timer();
        buttonTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            fv.setEnabled(true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {

                        }
                    }
                });
            }
        }, 500);
        */

        switch (v.getId()) {
            case R.id.btnBack:
                onBackPressed();
                break;
            case R.id.btnOnOff:
                if(!isConnectedDevice) {
                    showNotiMsg(LightDetailActivity.this,"스마트 조명이 연결되지 않았습니다.");
                } else if(power == POWER_ON) { //켜진상태
                    displayProgress(this, "","",2000);
                    MqttController.getInstance().publish(topicUpdateP,"{\"state\": {\"desired\" : {\"power\" : 0}}}");

                    btnOnOff.setText(getString(R.string.turn_off_light));
                    btnOnOff.setEnabled(true);
                    btnOnOff.setSelected(true);
                    seekBarDimLevel.setEnabled(true);
                    seekBarColorLevel.setEnabled(true);
                } else /*if(power == POWER_OFF)*/ { //꺼진상태
                    displayProgress(this, "","",2000);
                    MqttController.getInstance().publish(topicUpdateP,"{\"state\": {\"desired\" : {\"power\" : 1}}}");

                    btnOnOff.setText(getString(R.string.turn_on_light));
                    btnOnOff.setEnabled(true);
                    btnOnOff.setSelected(false);
                    seekBarDimLevel.setEnabled(false);
                    seekBarColorLevel.setEnabled(false);
                }
                break;
            case R.id.btnSetting:{
                Intent intent = new Intent(this, DeviceSettingActivity.class);
                intent.putExtra(EXTRA_DEVICE_INFO, (Parcelable) deviceInfo);
                startActivityForResult(intent, RESULT_UPDATE_DATA);
                }
                break;
            case R.id.btnEdit:{
                Intent intent = new Intent(this, PopupActivity.class);
                intent.putExtra(PopupActivity.POPUP_MODE, PopupActivity.MODE_INPUT);
                Bundle b = new Bundle();
                if (txtLightName.getText().toString().isEmpty()) {
                    b.putString(PopupActivity.POPUP_INPUT, "");
                } else {
                    b.putString(PopupActivity.POPUP_INPUT, txtLightName.getText().toString());
                }
                intent.putExtra(POPUP_BUNDLE, b);
                intent.putExtra(PopupActivity.POPUP_TITLE_TEXT, getString(R.string.change_device_name));
                startActivityForResult(intent, RESULT_INPUT_DEVICE_NAME);
                }
                break;

            case R.id.btnJaesilOnOff:
                if(powerJaesil == NOTING) {
                    showNotiMsg(LightDetailActivity.this,"재실센서가 동작되지 않습니다.");
                } else if(powerJaesil == POWER_OFF) {
                    displayProgress(LightDetailActivity.this, "","",2000);
                    changeSetTime(true, POWER_ON, mSelectJaesilTime, 0);
                } else if(powerJaesil == POWER_ON){
                    displayProgress(LightDetailActivity.this, "","",2000);
                    changeSetTime(true, POWER_OFF, mSelectJaesilTime, 0);
                }
                break;
            case R.id.btnJaesilTime: {
                Intent intent = new Intent(this, PopupActivity.class);
                intent.putExtra(PopupActivity.POPUP_MODE, PopupActivity.MODE_SET_JAESIL_TIME);
                intent.putExtra(POPUP_TIME_INDEX, 60);
                startActivityForResult(intent, RESULT_CHANGE_JAESIL_TIME);
                }
                break;
            case R.id.layoutModeLife:
                displayProgress(this, "","",2000);
                MqttController.getInstance().publish(topicUpdateP,"{\"state\": {\"desired\" : {\"power\" : 1, \"dimm\" : 10, \"temp\" : 8}}}");
                break;
            case R.id.layoutModeRead:
                displayProgress(this, "","",2000);
                MqttController.getInstance().publish(topicUpdateP,"{\"state\": {\"desired\" : {\"power\" : 1, \"dimm\" : 20, \"temp\" : 14}}}");
                break;
            case R.id.layoutModeStudy:
                displayProgress(this, "","",2000);
                MqttController.getInstance().publish(topicUpdateP,"{\"state\": {\"desired\" : {\"power\" : 1, \"dimm\" : 20, \"temp\" : 20}}}");
                break;
            case R.id.btnJaesilInfo:
                startActivity(new Intent(this, JaesilModeActivity.class));
                break;
        }
    }

    private void initUI() {
        txtLightName = findViewById(R.id.txtLightName);
        txtGroupName = findViewById(R.id.txtGroupName);
        btnOnOff = findViewById(R.id.btnOnOff);
        btnEdit = findViewById(R.id.btnEdit);
        seekBarDimLevel = findViewById(R.id.seekBarDimLevel);
        seekBarColorLevel = findViewById(R.id.seekBarColorLevel);
        layoutModeLife = findViewById(R.id.layoutModeLife);
        layoutModeRead = findViewById(R.id.layoutModeRead);
        layoutModeStudy = findViewById(R.id.layoutModeStudy);

        txtLightName.setText(deviceInfo.friendlyName.isEmpty()?deviceInfo.sharedFriendlyName.isEmpty()?getString(R.string.no_name):deviceInfo.sharedFriendlyName:deviceInfo.friendlyName);
        txtGroupName.setText(deviceInfo.dgroupName);
        if(isConnectedDevice) {
            btnOnOff.setText(getString(R.string.turn_on_light));
            seekBarDimLevel.setProgress(0);
            seekBarColorLevel.setProgress(0);
            seekBarDimLevel.setEnabled(false);
            seekBarColorLevel.setEnabled(false);
            layoutModeLife.setEnabled(true);
            layoutModeRead.setEnabled(true);
            layoutModeStudy.setEnabled(true);
            findViewById(R.id.btnJaesilOnOff).setEnabled(true);
            findViewById(R.id.btnJaesilTime).setEnabled(true);
        } else {
            btnOnOff.setText(getString(R.string.not_connected));
            btnOnOff.setEnabled(false);
            seekBarDimLevel.setProgress(0);
            seekBarColorLevel.setProgress(0);
            seekBarDimLevel.setEnabled(false);
            seekBarColorLevel.setEnabled(false);
            layoutModeLife.setEnabled(false);
            layoutModeRead.setEnabled(false);
            layoutModeStudy.setEnabled(false);
            findViewById(R.id.btnJaesilOnOff).setEnabled(false);
            findViewById(R.id.btnJaesilTime).setEnabled(false);
        }

        //마스터 조명의 경우 friendlyName이 없음, 없는 경우 조명 이름 수정 불가능하게 수정.
        if(deviceInfo.friendlyName.isEmpty()) {
            btnEdit.setVisibility(View.INVISIBLE);
        } else {
            btnEdit.setVisibility(View.VISIBLE);
        }


        seekBarDimLevel.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                /*
                if(progress != dimming) {
                    MqttController.getInstance().publish(topicUpdateP,"{\"state\": {\"desired\" : {\"dimm\" : "+(progress+1)+"}}}");
                }
                 */
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(seekBar.getProgress() != dimming) {
                    displayProgress(LightDetailActivity.this, "","",2000);
                    MqttController.getInstance().publish(topicUpdateP,"{\"state\": {\"desired\" : {\"dimm\" : "+(seekBar.getProgress()+1)+"}}}");
                }
            }
        });

        seekBarColorLevel.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                /*
                if(progress != colorTemp) {
                    MqttController.getInstance().publish(topicUpdateP,"{\"state\": {\"desired\" : {\"temp\" : "+(progress+1)+"}}}");
                }
                 */
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(seekBar.getProgress() != colorTemp) {
                    displayProgress(LightDetailActivity.this, "","",2000);
                    MqttController.getInstance().publish(topicUpdateP,"{\"state\": {\"desired\" : {\"temp\" : "+(seekBar.getProgress()+1)+"}}}");
                }
            }
        });
    }

    private void setControllMqtt() {
        MqttController.getInstance().subscribeToTopic(topicGetS1, new AWSIotMqttNewMessageCallback() {
            @Override
            public void onMessageArrived(String topic, byte[] data) {
                DebugLogOutput(TAG, "MQTT SUB / "+topic + "\n" + new String(data));
                changeUI(new String(data));
                MqttController.getInstance().unsubscribeToTopic(topicGetS1);
            }
        });

        MqttController.getInstance().subscribeToTopic(topicUpdateS1, new AWSIotMqttNewMessageCallback() {
            @Override
            public void onMessageArrived(String topic, byte[] data) {
                DebugLogOutput(TAG, "MQTT SUB / "+topic + "\n" + new String(data));
                changeUI(new String(data));
                if(IsRunningProgress()){
                    DismissConnectDialog();
                }
            }
        });

        MqttController.getInstance().subscribeToTopic(topicUpdateS2, new AWSIotMqttNewMessageCallback() {
            @Override
            public void onMessageArrived(String topic, byte[] data) {
                DebugLogOutput(TAG, "MQTT SUB / "+topic + "\n" + new String(data));
                //TODO 오류 발생 로직 구현.
            }
        });

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                MqttController.getInstance().publish(topicGetP,"{\"msgId\" : \""+UUID.randomUUID().toString()+"\"}");
                //MqttController.getInstance().publish(topicGetP,"{\"msgId\" : \""+deviceInfo.deviceId+"\"}");
            }
        },MQTT_PUBLISH_DELAY_TIME);
    }

    private void changeUI(final String data) {
        int temp_power = NOTING;
        int temp_dimming = NOTING;
        int temp_colorTemp = NOTING;

        try {
            JSONObject jsonObject = new JSONObject(data);

            if(!jsonObject.isNull("data")) {//Get status topic
                isConnectedDevice = true;
                JSONObject jsonState = jsonObject.getJSONObject("data");
                if (!jsonState.isNull("state")) {
                    JSONObject jsonReported = jsonState.getJSONObject("state");
                    //Power
                    if (!jsonReported.isNull("power")) {
                        //power off
                        temp_power = jsonReported.getInt("power");

                    }
                    //dimming
                    if (!jsonReported.isNull("dimm")) {
                        temp_dimming = jsonReported.getInt("dimm");
                    }

                    //colorTemp
                    if (!jsonReported.isNull("temp")) {
                        temp_colorTemp = jsonReported.getInt("temp");
                    }
                }
            } else if(!jsonObject.isNull("state")) {  //Update topic
                JSONObject jsonState = jsonObject.getJSONObject("state");
                if (!jsonState.isNull("reported")) {
                    JSONObject jsonReported = jsonState.getJSONObject("reported");
                    //Power
                    if (!jsonReported.isNull("power")) {
                        //power off
                        temp_power = jsonReported.getInt("power");

                    }
                    //dimming
                    if (!jsonReported.isNull("dimm")) {
                        temp_dimming = jsonReported.getInt("dimm");
                    }

                    //colorTemp
                    if (!jsonReported.isNull("temp")) {
                        temp_colorTemp = jsonReported.getInt("temp");
                    }
                }

                if (!jsonState.isNull("desired")) {
                    JSONObject jsonDesired = jsonState.getJSONObject("desired");
                    //Power
                    if (!jsonDesired.isNull("power")) {
                        //power off
                        temp_power = jsonDesired.getInt("power");

                    }
                    //dimming
                    if (!jsonDesired.isNull("dimm")) {
                        temp_dimming = jsonDesired.getInt("dimm");
                    }

                    //colorTemp
                    if (!jsonDesired.isNull("temp")) {
                        temp_colorTemp = jsonDesired.getInt("temp");
                    }
                }

                if(!jsonState.isNull("power")) {
                    temp_power = jsonState.getInt("power");
                }

                if(!jsonState.isNull("dimm")) {
                    temp_dimming = jsonState.getInt("dimm");
                }

                if(!jsonState.isNull("temp")) {
                    temp_colorTemp = jsonState.getInt("temp");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        final int powerFix = temp_power;
        final int dimmingFix = temp_dimming;
        final int colorTempFix = temp_colorTemp;

        if(temp_power != NOTING) {
            power = temp_power;
        }

        if(temp_dimming != NOTING) {
            dimming = temp_dimming;
        }


        if(temp_colorTemp == NOTING) {
            colorTemp = temp_colorTemp;
        }

        DebugLogOutput(TAG, "LIGHT_STATUS - power : "+powerFix + " / dimm : " + dimmingFix + " / tempFix : " + colorTempFix);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if(!isConnectedDevice) {
                    btnOnOff.setText(getString(R.string.not_connected));
                    btnOnOff.setEnabled(false);
                    seekBarDimLevel.setEnabled(false);
                    seekBarColorLevel.setEnabled(false);
                    layoutModeLife.setEnabled(false);
                    layoutModeRead.setEnabled(false);
                    layoutModeStudy.setEnabled(false);
                } else if(powerFix == POWER_OFF) {
                    btnOnOff.setText(getString(R.string.turn_on_light));
                    btnOnOff.setEnabled(true);
                    btnOnOff.setSelected(false);
                    seekBarDimLevel.setEnabled(false);
                    seekBarColorLevel.setEnabled(false);
                    layoutModeLife.setEnabled(true);
                    layoutModeRead.setEnabled(true);
                    layoutModeStudy.setEnabled(true);
                } else if(powerFix == POWER_ON) {
                    btnOnOff.setText(getString(R.string.turn_off_light));
                    btnOnOff.setEnabled(true);
                    btnOnOff.setSelected(true);
                    seekBarDimLevel.setEnabled(true);
                    seekBarColorLevel.setEnabled(true);
                    layoutModeLife.setEnabled(true);
                    layoutModeRead.setEnabled(true);
                    layoutModeStudy.setEnabled(true);
                }

                if(dimmingFix != NOTING) {
                    seekBarDimLevel.setProgress(dimmingFix-1);
                }

                if(colorTempFix != NOTING) {
                    seekBarColorLevel.setProgress(colorTempFix-1);
                }
            }
        });
    }

    private void getJaesilData() {
        MqttController.getInstance().subscribeToTopic(topicJaesilGetS1, new AWSIotMqttNewMessageCallback() {
            @Override
            public void onMessageArrived(String topic, byte[] data) {
                DebugLogOutput(TAG, "MQTT SUB / "+topic + "\n" + new String(data));
                parsingData(new String(data));
                MqttController.getInstance().unsubscribeToTopic(topicJaesilGetS1);
            }
        });

        MqttController.getInstance().subscribeToTopic(topicJaesilSetS1, new AWSIotMqttNewMessageCallback() {
            @Override
            public void onMessageArrived(String topic, byte[] data) {
                DebugLogOutput(TAG, "MQTT SUB / "+topic + "\n" + new String(data));
                parsingData(new String(data));
                if(IsRunningProgress()){
                    DismissConnectDialog();
                }
            }
        });

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                MqttController.getInstance().publish(topicJaesilGetP,"{}");
            }
        },MQTT_PUBLISH_DELAY_TIME);
    }

    private void parsingData(final String data) {
        int temp_power = NOTING;
        int temp_time = NOTING;
        int temp_step = NOTING;

        try {
            JSONObject jsonObject = new JSONObject(data);

            if(!jsonObject.isNull("state")) {  //Update topic
                JSONObject jsonState = jsonObject.getJSONObject("state");
                if (!jsonState.isNull("reported")) {
                    JSONObject jsonReported = jsonState.getJSONObject("reported");
                    //Power
                    if (!jsonReported.isNull("sse")) {
                        //power off
                        temp_power = jsonReported.getInt("sse");

                    }
                    //Time
                    if (!jsonReported.isNull("sot")) {
                        temp_time = jsonReported.getInt("sot");
                    }

                    //Jaesil Statu
                    if (!jsonReported.isNull("sn")) {
                        temp_step = jsonReported.getInt("sn");
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        final int powerFix = temp_power;
        final int timeFix = temp_time;
        final int stepFix = temp_step;

        if(powerFix != NOTING && timeFix != NOTING && stepFix != NOTING) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    findViewById(R.id.btnJaesilOnOff).setEnabled(true);
                    changeSetTime(false, powerFix, timeFix, stepFix);
                }
            });
        }
    }

    private void changeSetTime(boolean send, int onOff, int time, int step) {
        mSelectJaesilTime = time;
        powerJaesil = onOff;
        findViewById(R.id.btnJaesilOnOff).setSelected(onOff==POWER_ON?true:false);
        ((TextView)findViewById(R.id.txtJaesilOnOff)).setText(onOff==POWER_ON?getString(R.string.on2):getString(R.string.off2));
        ((TextView)findViewById(R.id.txtStatusJaesil)).setText(onOff==POWER_ON?getText(R.string.jaesil_on):getText(R.string.jaesil_off));

        findViewById(R.id.btnJaesilTime).setEnabled(onOff==POWER_ON?true:false);
        switch (mSelectJaesilTime) {
            case 120:
                ((TextView)findViewById(R.id.txtJaesilTime)).setText("2시간");
                break;
            case 90:
                ((TextView)findViewById(R.id.txtJaesilTime)).setText("1시간 30분");
                break;
            case 60:
            default:
                ((TextView)findViewById(R.id.txtJaesilTime)).setText("1시간");
                break;
            case 50:
                ((TextView)findViewById(R.id.txtJaesilTime)).setText("50분");
                break;
            case 40:
                ((TextView)findViewById(R.id.txtJaesilTime)).setText("40분");
                break;
            case 30:
                ((TextView)findViewById(R.id.txtJaesilTime)).setText("30분");
                break;
            case 20:
                ((TextView)findViewById(R.id.txtJaesilTime)).setText("20분");
                break;
            case 10:
                ((TextView)findViewById(R.id.txtJaesilTime)).setText("10분");
                break;
            case 5:
                ((TextView)findViewById(R.id.txtJaesilTime)).setText("5분");
                break;
        }

        if(send) {
            isChangeData = true;
            setJaesil(onOff, time, step);
        }
    }

    private void setJaesil(int onOff, int time, int step) {
        String payload = "{\n" +
                "\"state\": {\n" +
                "\"reported\" : {\n" +
                "\"sse\" : " + onOff + ",\n" +
                "\"sot\" : " + time + ",\n" +
                "\"sn\" : " + step + "\n" +
                "}\n" +
                "}\n" +
                "}";
        MqttController.getInstance().publish(topicJaesilSetP,payload);
    }

    private void changeDeviceName(final String name) {
        displayProgress(this,"","");
        try {
            HttpApi.modifyDeviceInfo(deviceInfo.deviceId,
                    name,
                    new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.modifyDeviceInfo(onFailure)\n" + e.toString());
                            showNotiMsg(LightDetailActivity.this,getString(R.string.snackbar_fail_change_device_name));
                            DismissConnectDialog();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if(response.code() == HttpApi.HTTP_NO_CONTENT) {
                                WarnLogOutput(TAG, "HttpApi.modifyDeviceInfo(onResponse) HTTP_NO_CONTENT");

                                final DeviceInfo itemS = DBUtil.getDeviceInfoForId(TABLE_SMART_LIGHT,deviceInfo.deviceId);
                                if(itemS != null) {
                                    itemS.friendlyName = name;
                                    DBUtil.updateDeviceItem(TABLE_SMART_LIGHT,itemS);
                                }

                                final DeviceInfo itemH = DBUtil.getDeviceInfoForId(TABLE_DEVICE_HOME,deviceInfo.deviceId);
                                if(itemH != null) {
                                    itemH.friendlyName = name;
                                    DBUtil.updateDeviceItem(TABLE_DEVICE_HOME,itemH);
                                }

                                final DeviceInfo itemR = DBUtil.getDeviceInfoForId(TABLE_DEVICE_RANK,deviceInfo.deviceId);
                                if(itemR != null) {
                                    itemR.friendlyName = name;
                                    DBUtil.updateDeviceItem(TABLE_DEVICE_RANK,itemR);
                                }

                                isChangeData = true;
                                deviceInfo.friendlyName = name;
                                for(int i = 0 ; i < UserInfo.devices.size() ; i++) {
                                    if(UserInfo.devices.get(i).deviceId.equals(deviceInfo.deviceId)) {
                                        if(!UserInfo.devices.get(i).friendlyName.equals(deviceInfo.friendlyName)) {
                                            UserInfo.devices.get(i).friendlyName = deviceInfo.friendlyName;
                                        }
                                    }
                                }

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        showNotiMsg(LightDetailActivity.this,getString(R.string.snackbar_successed_change_device_name));
                                        txtLightName.setText(deviceInfo.friendlyName);
                                        DismissConnectDialog();
                                    }
                                });
                            } else {
                                ErrorLogOutput(TAG, "HttpApi.modifyDeviceInfo(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                showNotiMsg(LightDetailActivity.this,getString(R.string.snackbar_fail_change_device_name));
                                DismissConnectDialog();
                                try {
                                    JSONObject json_data = new JSONObject(response.body().string());
                                    ErrorLogOutput(TAG, "HttpApi.modifyDeviceInfo(onResponse) body : " + json_data.toString());
                                } catch (JSONException e) {
                                    ErrorLogOutput(TAG, "HttpApi.modifyDeviceInfo(onResponse) JSONException : " + e.toString());
                                }
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.modifyDeviceInfo(Exception)\n" + e.toString());
            showNotiMsg(LightDetailActivity.this,getString(R.string.snackbar_fail_change_device_name));
            DismissConnectDialog();
        }
    }
}