package kr.co.icontrols.iotplatform;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.amazonaws.mobileconnectors.iot.AWSIotMqttNewMessageCallback;

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

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

import kr.co.icontrols.iotplatform.DataClass.DeviceGroupInfo;
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.utils.HttpApi;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static kr.co.icontrols.iotplatform.Database.DatabaseHelper.TABLE_SMART_LIGHT;
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.WarnLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.displayProgress;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.showNotiMsg;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_DEVICE_ID;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_DEVICE_INFO;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_DEVICE_NAME;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_GROUP_ID;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_GROUP_LIST;
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.RESULT_ADD_HOME_CONFIRM;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_INIT_DEVICE_CONFIRM;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_UPDATE_DATA;
import static kr.co.icontrols.iotplatform.utils.HttpApi.HTTP_OK;

public class DeviceSettingActivity extends AppCompatActivity implements View.OnClickListener {

    private String TAG = "DeviceSettingActivity";
    private DeviceInfo deviceInfo;
    private Button btnInit;
    private TextView txtDeviceName, txtGroupName, txtAddHomeStatus;
    private boolean isChangeData;
    private String currentVersionForFirmware, newVersionForFirmware, detailDeviceInfo;
    private LinearLayout layoutFirmware;

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

        isChangeData = false;
        newVersionForFirmware = "";
        currentVersionForFirmware = "";
        detailDeviceInfo = "";

        deviceInfo = getIntent().getParcelableExtra(EXTRA_DEVICE_INFO);

        txtDeviceName = findViewById(R.id.txtDeviceName);
        txtGroupName = findViewById(R.id.txtGroupName);
        txtAddHomeStatus = findViewById(R.id.txtAddHomeStatus);

        txtDeviceName.setText(deviceInfo.friendlyName.isEmpty()?deviceInfo.sharedFriendlyName.isEmpty()?getString(R.string.no_name):deviceInfo.sharedFriendlyName:deviceInfo.friendlyName);
        txtGroupName.setText(deviceInfo.dgroupName);

        layoutFirmware = findViewById(R.id.layoutFirmware);

        //마스터 스마트 조명의 경우 friendlyName이 없음, 없는 경우 스마트 조명 초기화 불가능하게 수정.
        btnInit = findViewById(R.id.btnInit);
        if(deviceInfo.friendlyName.isEmpty()) {
            btnInit.setEnabled(false);
        } else {
            btnInit.setEnabled(true);
        }

        if(DBUtil.getDeviceInfoForId(TABLE_SMART_LIGHT,deviceInfo.deviceId) == null) {
            txtAddHomeStatus.setText(getString(R.string.no_added));
        } else {
            txtAddHomeStatus.setText(getString(R.string.added));
        }

        getNewVersionForFirmware();
    }

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

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

    @Override
    protected void onPause() {
        MqttController.getInstance().allUnsubscribeToTopics();
        super.onPause();
    }

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

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_ADD_HOME_CONFIRM:
                if(resultCode == Activity.RESULT_OK) {
                    isChangeData = true;
                    if(DBUtil.getDeviceInfoForId(TABLE_SMART_LIGHT,deviceInfo.deviceId) == null) {
                        if (DBUtil.putDeviceInfo(TABLE_SMART_LIGHT, deviceInfo) != -1) {
                            showNotiMsg(DeviceSettingActivity.this, "홈에 추가되었습니다.");
                            txtAddHomeStatus.setText(getString(R.string.added));
                        } else {
                            showNotiMsg(DeviceSettingActivity.this, "홈에 추가를 실패하였습니다.");
                        }
                    } else {
                        DBUtil.removeDeviceInfo(TABLE_SMART_LIGHT, deviceInfo);
                        showNotiMsg(DeviceSettingActivity.this, "홈에서 제거 되었습니다.");
                        txtAddHomeStatus.setText(getString(R.string.no_added));
                    }
                } else {

                }
                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_INIT_DEVICE_CONFIRM:
                if(resultCode == RESULT_OK) {
                    displayProgress(this,null,null);
                    try {
                        final String deviceId = deviceInfo.deviceId;
                        HttpApi.deleteDevice(deviceInfo.deviceId, new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                e.printStackTrace();
                                ErrorLogOutput(TAG, "HttpApi.deleteDevice(onFailure)\n" + e.toString());
                                showNotiMsg(DeviceSettingActivity.this,"스마트 조명을 초기화를 실패하였습니다.");
                                DismissConnectDialog();
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                if (response.code() == HttpApi.HTTP_NO_CONTENT) {
                                    WarnLogOutput(TAG, "HttpApi.deleteDevice(onResponse) HTTP_NO_CONTENT");
                                    DBUtil.removeDeviceInfoAtAllTable(deviceId);
                                    for(int i = 0 ; i < UserInfo.devices.size() ; i++) {
                                        if(UserInfo.devices.get(i).deviceId.equals(deviceId)) {
                                            UserInfo.devices.remove(i);
                                            i--;
                                        }
                                    }
                                    showNotiMsg(DeviceSettingActivity.this,"스마트 조명을 초기화를 하였습니다.",DeviceActivity.class);
                                } else {
                                    ErrorLogOutput(TAG, "HttpApi.deleteDevice(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                    showNotiMsg(DeviceSettingActivity.this,"스마트 조명을 초기화를 실패하였습니다.");

                                    try {
                                        JSONObject json_data = new JSONObject(response.body().string());
                                        ErrorLogOutput(TAG, "HttpApi.deleteDevice(onResponse) body : " + json_data.toString());
                                    } catch (JSONException e) {
                                        ErrorLogOutput(TAG, "HttpApi.deleteDevice(onResponse) JSONException : " + e.toString());
                                    }
                                }
                                DismissConnectDialog();
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        ErrorLogOutput(TAG, "HttpApi.deleteDevice(Exception)\n" + e.toString());
                        showNotiMsg(DeviceSettingActivity.this,"스마트 조명을 초기화를 실패하였습니다.");
                        DismissConnectDialog();

                    }
                }
                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.layoutGroup:
                getMyDeviceGroup();
                break;
            case R.id.layoutAddHome:{
                Intent intent = new Intent(DeviceSettingActivity.this,PopupActivity.class);
                intent.putExtra(PopupActivity.POPUP_MODE,PopupActivity.MODE_YESNO);
                if(DBUtil.getDeviceInfoForId(TABLE_SMART_LIGHT,deviceInfo.deviceId) == null) {
                    intent.putExtra(PopupActivity.POPUP_TITLE_TEXT,String.format(getString(R.string.popup_confirm_add_home),deviceInfo.friendlyName.isEmpty()?deviceInfo.sharedFriendlyName.isEmpty()?getString(R.string.no_name):deviceInfo.sharedFriendlyName:deviceInfo.friendlyName));
                } else {
                    intent.putExtra(PopupActivity.POPUP_TITLE_TEXT,String.format(getString(R.string.popup_confirm_remove_home),deviceInfo.friendlyName.isEmpty()?deviceInfo.sharedFriendlyName.isEmpty()?getString(R.string.no_name):deviceInfo.sharedFriendlyName:deviceInfo.friendlyName));
                }
                startActivityForResult(intent,RESULT_ADD_HOME_CONFIRM);
                }
                break;
            case R.id.layoutJaesil:{
                Intent intent = new Intent(this, JaesilModeActivity.class);
                intent.putExtra(EXTRA_DEVICE_INFO, (Parcelable) deviceInfo);
                startActivityForResult(intent, RESULT_UPDATE_DATA);
                }
                break;
            case R.id.layoutDeviceInfo:
                //getDetailDeviceInfo();
                if(detailDeviceInfo.isEmpty()){
                    showNotiMsg(this, "디바이스 정보를 획득하지 못하였습니다.");
                } else {
                    Intent intent = new Intent(DeviceSettingActivity.this, PopupActivity.class);
                    intent.putExtra(PopupActivity.POPUP_MODE, PopupActivity.MODE_NORMAL);
                    intent.putExtra(PopupActivity.POPUP_TITLE_TEXT, "디바이스 정보");
                    intent.putExtra(PopupActivity.POPUP_BODY_TEXT, detailDeviceInfo);
                    startActivity(intent);
                }
                break;
            case R.id.layoutFirmware:
                updateFirmware();
                break;
            case R.id.btnInit: {
                Intent intent = new Intent(this, PopupActivity.class);
                intent.putExtra(PopupActivity.POPUP_MODE, PopupActivity.MODE_YESNO_WITH_ICON);
                intent.putExtra(PopupActivity.POPUP_TITLE_TEXT, String.format(getString(R.string.popup_init_device_confirm),deviceInfo.friendlyName));
                intent.putExtra(PopupActivity.POPUP_OK_BUTTON_TEXT, getString(R.string.init));
                intent.putExtra(PopupActivity.POPUP_CANCEL_BUTTON_TEXT, getString(R.string.cancel));
                startActivityForResult(intent, RESULT_INIT_DEVICE_CONFIRM);
                }
                break;
        }
    }


    public void getMyDeviceGroup(){
        UserInfo.getGroup(this, new UserInfo.CallbackForUpdate() {
            @Override
            public void updateData() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(UserInfo.dgroups.size() == 0) {
                            showNotiMsg(DeviceSettingActivity.this, "변경할 그룹이 존재하지 않습니다.");
                        } else {
                            UserInfo.setUnSelectAllGroups();
                            Intent intent = new Intent(DeviceSettingActivity.this, GroupSelectActivity.class);
                            intent.putExtra("MODE","SELECT");
                            intent.putExtra(EXTRA_GROUP_LIST, UserInfo.dgroups);
                            intent.putExtra(EXTRA_DEVICE_ID, deviceInfo.deviceId);
                            intent.putExtra(EXTRA_DEVICE_NAME, deviceInfo.friendlyName.isEmpty()?deviceInfo.sharedFriendlyName.isEmpty()?getString(R.string.no_name):deviceInfo.sharedFriendlyName:deviceInfo.friendlyName);
                            intent.putExtra(EXTRA_GROUP_ID, deviceInfo.dgroupId);
                            startActivityForResult(intent,RESULT_UPDATE_DATA);
                        };
                    }
                });
            }
        });

        /*
        if(mGroupList != null) {
            mGroupList.clear();
        } else {
            mGroupList = new ArrayList<>();
        }
        displayProgress(this,"","");
        try {
            HttpApi.getDeviceGroupList(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    ErrorLogOutput(TAG, "HttpApi.getDeviceGroupList(onFailure)\n" + e.toString());
                    DismissConnectDialog();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if(response.code() == HTTP_OK) {
                        WarnLogOutput(TAG, "HttpApi.getDeviceGroupList(onResponse) : HTTP_OK");
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            JSONArray jarrayAll = new JSONArray(json_data.getString("results"));

                            for (int i = 0; i < jarrayAll.length(); i++) {
                                JSONObject jObject = jarrayAll.getJSONObject(i);
                                DeviceGroupInfo item = new DeviceGroupInfo(jObject.isNull("dgroupId") ? "" : jObject.getString("dgroupId"),
                                        jObject.isNull("friendlyName") ? "" : jObject.getString("friendlyName"),
                                        jObject.isNull("icon") ? "" : jObject.getString("icon"),
                                        jObject.isNull("index") ? 99 : jObject.getInt("index"));

                                mGroupList.add(item);
                            }

                            //UI 업데이트
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(mGroupList.size() == 0) {
                                        showNotiMsg(DeviceSettingActivity.this, "변경할 그룹이 존재하지 않습니다.");
                                    } else {
                                        Intent intent = new Intent(DeviceSettingActivity.this, GroupSelectActivity.class);
                                        intent.putExtra("MODE","SELECT");
                                        intent.putExtra(EXTRA_GROUP_LIST, mGroupList);
                                        intent.putExtra(EXTRA_DEVICE_ID, deviceInfo.deviceId);
                                        intent.putExtra(EXTRA_DEVICE_NAME, deviceInfo.friendlyName);
                                        intent.putExtra(EXTRA_GROUP_ID, deviceInfo.dgroupId);
                                        startActivityForResult(intent,RESULT_UPDATE_DATA);
                                    }
                                    DismissConnectDialog();
                                }
                            });

                        } catch (JSONException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.getDeviceGroupList(JSONException)\n" + e.toString());
                            DismissConnectDialog();
                        }
                    } else {
                        ErrorLogOutput(TAG, "HttpApi.getDeviceGroupList(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            ErrorLogOutput(TAG, "HttpApi.getDeviceGroupList(onResponse) body : " + json_data.toString());
                        } catch (JSONException e) {
                            ErrorLogOutput(TAG, "HttpApi.getDeviceGroupList(onResponse) JSONException : " + e.toString());
                        }
                        DismissConnectDialog();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.getDeviceGroupList(Exception)\n" + e.toString());
            DismissConnectDialog();
        }
         */
    }

    public void getDetailDeviceInfo(){
        try {
            HttpApi.getDeviceInfo(deviceInfo.deviceId, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    ErrorLogOutput(TAG, "HttpApi.getDeviceInfo(onFailure)\n" + e.toString());
                    DismissConnectDialog();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if(response.code() == HTTP_OK) {
                        WarnLogOutput(TAG, "HttpApi.getDeviceInfo(onResponse) : HTTP_OK");
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());

                            detailDeviceInfo = "deviceId : " + (json_data.isNull("deviceId") ? "" : json_data.getString("deviceId"))
                                    + "\ndeviceType : " + (json_data.isNull("deviceType") ? "" : json_data.getString("deviceType"))
                                    + "\nfirmwareVersion : " + (json_data.isNull("firmwareVersion") ? "" : json_data.getString("firmwareVersion"))
                                    + "\nfriendlyName : " + (json_data.isNull("friendlyName") ? "" : json_data.getString("friendlyName"))
                                    + "\nsharedFriendlyName : " + (json_data.isNull("sharedFriendlyName") ? "" : json_data.getString("sharedFriendlyName"))
                                    + "\nownerId : " + (json_data.isNull("ownerId") ? "" : json_data.getString("ownerId"))
                                    + "\ndgroupId : " + (json_data.isNull("dgroupId") ? "" : json_data.getString("dgroupId"))
                                    + "\ndgroupName : " + (json_data.isNull("dgroupName") ? "" : json_data.getString("dgroupName"));

                            currentVersionForFirmware = json_data.isNull("firmwareVersion") ? "" : json_data.getString("firmwareVersion");

                            //UI 업데이트
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showFirmwareMenu();
                                    DismissConnectDialog();
                                }
                            });

                        } catch (JSONException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.getDeviceInfo(JSONException)\n" + e.toString());
                            DismissConnectDialog();
                        }
                    } else {
                        ErrorLogOutput(TAG, "HttpApi.getDeviceInfo(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            ErrorLogOutput(TAG, "HttpApi.getDeviceInfo(onResponse) body : " + json_data.toString());
                        } catch (JSONException e) {
                            ErrorLogOutput(TAG, "HttpApi.getDeviceInfo(onResponse) JSONException : " + e.toString());
                        }
                        DismissConnectDialog();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.getDeviceInfo(Exception)\n" + e.toString());
            DismissConnectDialog();
        }
    }

    private void getJaesilData() {

        final String topicGetP = String.format(getString(R.string.topic_get_jaesil_data),deviceInfo.deviceId);
        final String topicGetS1 = String.format(getString(R.string.topic_response_get_jaesil_data),deviceInfo.deviceId);

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

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

                int temp_power = NOTING;

                try {
                    JSONObject jsonObject = new JSONObject(new String(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");

                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                final int powerFix = temp_power;
                if(powerFix != NOTING) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ((TextView)findViewById(R.id.txtJaesilStatus)).setText(getString(powerFix == 1?R.string.on:R.string.off));
                        }
                    });
                }
                MqttController.getInstance().unsubscribeToTopic(topicGetS1);
            }
        });
    }

    private void getNewVersionForFirmware() {
        displayProgress(this,"","");
        try {
            HttpApi.getFirmwareInfoAtDevice(deviceInfo.deviceId, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    ErrorLogOutput(TAG, "HttpApi.getFirmwareInfoAtDevice(onFailure)\n" + e.toString());
                    showNotiMsg(DeviceSettingActivity.this,"스마트 조명 최신 펌웨어 정보 획득을 실패하였습니다.");
                    DismissConnectDialog();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.code() == HttpApi.HTTP_OK) {
                        WarnLogOutput(TAG, "HttpApi.getFirmwareInfoAtDevice(onResponse) HTTP_OK");
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            newVersionForFirmware = json_data.isNull("version") ? "" : json_data.getString("version");
                            DebugLogOutput(TAG, "new Firmware Version : " + newVersionForFirmware);

                            getDetailDeviceInfo();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    } else {
                        ErrorLogOutput(TAG, "HttpApi.getFirmwareInfoAtDevice(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                        showNotiMsg(DeviceSettingActivity.this,"스마트 조명 최신 펌웨어 정보 획득을 실패하였습니다.");

                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            ErrorLogOutput(TAG, "HttpApi.getFirmwareInfoAtDevice(onResponse) body : " + json_data.toString());
                        } catch (JSONException e) {
                            ErrorLogOutput(TAG, "HttpApi.getFirmwareInfoAtDevice(onResponse) JSONException : " + e.toString());
                        }
                    }
                    DismissConnectDialog();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.getFirmwareInfoAtDevice(Exception)\n" + e.toString());
            showNotiMsg(DeviceSettingActivity.this,"스마트 조명 최신 펌웨어 정보 획득을 실패하였습니다.");
            DismissConnectDialog();
        }
    }

    private void updateFirmware() {
        displayProgress(this,"","");
        try {
            HttpApi.updateFirmwareInfoAtDevice(deviceInfo.deviceId, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    ErrorLogOutput(TAG, "HttpApi.updateFirmwareInfoAtDevice(onFailure)\n" + e.toString());
                    showNotiMsg(DeviceSettingActivity.this,"스마트 조명 최신 펌웨어 업데이트를 실패하였습니다.");
                    DismissConnectDialog();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.code() == HttpApi.HTTP_NO_CONTENT) {
                        WarnLogOutput(TAG, "HttpApi.updateFirmwareInfoAtDevice(onResponse) HTTP_NO_CONTENT");
                        showNotiMsg(DeviceSettingActivity.this,"스마트 조명 최신 펌웨어를 업데이트 하였습니다.");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                layoutFirmware.setVisibility(View.GONE);
                                DismissConnectDialog();
                            }
                        });
                    } else {
                        ErrorLogOutput(TAG, "HttpApi.updateFirmwareInfoAtDevice(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                        showNotiMsg(DeviceSettingActivity.this,"스마트 조명 최신 펌웨어 업데이트를 실패하였습니다.");

                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            ErrorLogOutput(TAG, "HttpApi.updateFirmwareInfoAtDevice(onResponse) body : " + json_data.toString());
                        } catch (JSONException e) {
                            ErrorLogOutput(TAG, "HttpApi.updateFirmwareInfoAtDevice(onResponse) JSONException : " + e.toString());
                        }
                        DismissConnectDialog();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.updateFirmwareInfoAtDevice(Exception)\n" + e.toString());
            showNotiMsg(DeviceSettingActivity.this,"스마트 조명 최신 펌웨어 업데이트를 실패하였습니다.");
            DismissConnectDialog();
        }
    }

    private void showFirmwareMenu() {
        if(currentVersionForFirmware.isEmpty() || newVersionForFirmware.isEmpty() || currentVersionForFirmware.equals(newVersionForFirmware)) {
            layoutFirmware.setVisibility(View.GONE);
        } else {
            layoutFirmware.setVisibility(View.VISIBLE);
        }
    }
}