package kr.co.icontrols.iotplatform;

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

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;

import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserDetails;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserSession;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttNewMessageCallback;

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

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;

import kr.co.icontrols.iotplatform.DataClass.DeviceInfo;
import kr.co.icontrols.iotplatform.DataClass.InviteInfo;
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.DeviceListAdapter;
import kr.co.icontrols.iotplatform.cognito.AppHelper;
import kr.co.icontrols.iotplatform.utils.GetSessionCallback;
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.DEFAULT_POPUP_TIMEOUT;
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.cancelToExit;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.displayProgress;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.getCognitoSession;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.goToLoginActivity;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.isExpiredSession;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.isRestartAppForBackgroundWaitTime;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.requestConfirmUser;
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.sendConfirmEmail;
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.EXTRA_DEVICE_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.POWER_OFF;
import static kr.co.icontrols.iotplatform.utils.Constants.POWER_ON;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_INVITE_CONFIRM;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_LOGOUT_SUCCESS;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_RESEND_CONFIRM;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_UPDATE_DATA;
import static kr.co.icontrols.iotplatform.utils.HttpApi.HTTP_OK;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private final String TAG = "MainActivity";

    private AlertDialog userDialog;
    private ProgressDialog waitDialog;
    private ListView attributesList;

    // Cognito user objects
    private CognitoUser user;
    private CognitoUserSession session;
    private CognitoUserDetails details;

    // User details
    private String username;

    //SMART LIGHT
    private ArrayList<DeviceInfo> smartLights = null;
    private LinearLayout layoutSmartLight[];
    private ImageView imgSmartLightIcon[];
    private TextView txtSmartLightName[];
    private TextView txtSmartLightGroupName[];
    private int smartLightPower[];

    //HOME DEVICE
    private ArrayList<DeviceInfo> homeDevices = null;
    private ArrayList<DeviceInfo> rankDevices = null;
    private ArrayList<InviteInfo> InviteInfos = null;

    private Handler mConnectedHandler;

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

        init();
        if(isExpiredSession()) {
            getCognitoSession(new GetSessionCallback() {
                @Override
                public void successed() {
                    getUserInfo();
                }

                @Override
                public void failed() {
                    showNotiMsg(MainActivity.this, "세션을 갱신하지 못하였습니다.");
                    System.exit(0);
                }
            });
        } else {
            getUserInfo();
        }

        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()) {
                    MqttController.getInstance().allUnsubscribeToTopics();
                    getSmartLightAndHome();
                } else {
                    mConnectedHandler.sendEmptyMessageDelayed(1,1000);
                }
            }
        };
    }

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

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

        if(UserInfo.deviceCount > 0) {
            MqttController.getInstance().allUnsubscribeToTopics();
            getSmartLightAndHome();

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

    }

    @Override
    protected void onPause() {
        mConnectedHandler.removeCallbacksAndMessages(null);
        MqttController.getInstance().allUnsubscribeToTopics();
        setBackgroundWaitTime();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        resetBackgroundWaitTime();

        if(InviteInfos != null) {
            InviteInfos.clear();
        }

        if(smartLights != null) {
            smartLights.clear();
        }

        if(homeDevices != null) {
            homeDevices.clear();
        }

        if(rankDevices != null) {
            rankDevices.clear();
        }

        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_INVITE_CONFIRM:
                if(resultCode == RESULT_OK) {
                    comfirmInvite(true);
                } else {
                    comfirmInvite(false);
                }
                break;
            case RESULT_UPDATE_DATA:
                if(resultCode == RESULT_OK) {
                    MqttController.getInstance().allUnsubscribeToTopics();
                    getSmartLightAndHome();
                }
                break;
            case RESULT_RESEND_CONFIRM:
                if(resultCode == RESULT_OK) {
                    requestConfirmUser(MainActivity.this);
                } else {
                    goToLoginActivity(MainActivity.this);
                }
                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);
        */

        if(!UserInfo.confirmed) {
            showNotiMsg(this, "인증 후 사용 가능합니다.");
            return;
        }

        switch (v.getId()) {
            case R.id.btnBack:
                break;
            case R.id.btnRight:
                //startActivity(new Intent(this, TestHttpApiActivity.class));
                //startActivity(new Intent(this, AddDeviceListActivity.class));
                startActivity(new Intent(this,LightRegisterGuideActivity.class));
                break;
            case R.id.btnRegisterDevice:
                //startActivity(new Intent(this, AddDeviceListActivity.class));
                startActivity(new Intent(this,LightRegisterGuideActivity.class));
                break;
            case R.id.btnRegisterLocation:
                startActivity(new Intent(this, RegisterLocationActivity.class));
                break;
            case R.id.btnAddHome:
                startActivityForResult(new Intent(this, AddHomeActivity.class),RESULT_UPDATE_DATA);
                break;
            case R.id.btnSmartLightMore:
                findViewById(R.id.layoutMore).setVisibility(View.VISIBLE);
                break;
            case R.id.btnCloseMore:
                findViewById(R.id.layoutMore).setVisibility(View.GONE);
                break;
            case R.id.layoutMoreAdd:
                if(smartLights.size() >= 4){
                    showNotiMsg(MainActivity.this, "스마트 조명은 4개까지만 등록 가능합니다.");
                } else {
                    findViewById(R.id.layoutMore).setVisibility(View.GONE);
                    startActivityForResult(new Intent(this, AddHomeActivity.class),RESULT_UPDATE_DATA);
                }
                break;
            case R.id.layoutMoreRank:
                findViewById(R.id.layoutMore).setVisibility(View.GONE);
                if(smartLights.size() > 1) {
                    Intent intent = new Intent(MainActivity.this, DeviceChangeRankActivity.class);
                    intent.putExtra(EXTRA_DEVICE_LIST, smartLights);
                    intent.putExtra("MODE","SMART_LIGHT");
                    startActivityForResult(intent,RESULT_UPDATE_DATA);
                } else {
                    showNotiMsg(MainActivity.this,"스마트 조명 갯수가 2개 이상에만 변경 가능합니다.");
                }
                break;
            case R.id.layoutMoreDelete: {
                findViewById(R.id.layoutMore).setVisibility(View.GONE);
                Intent intent = new Intent(MainActivity.this, DeviceSelectActivity.class);
                intent.putExtra("MODE", "SMART_LIGHT");
                intent.putExtra(EXTRA_DEVICE_LIST, smartLights);
                startActivityForResult(intent,RESULT_UPDATE_DATA);
                }
                break;
            case R.id.btnCloseInfo:
                findViewById(R.id.layoutInfo).setVisibility(View.GONE);
                break;
            case R.id.btnWeatherInfo:
                findViewById(R.id.layoutInfo).setVisibility(View.VISIBLE);
                break;
            case R.id.layoutSmartDevice:
            case R.id.layoutSmartInfo:
                Intent intent = new Intent(this, PopupActivity.class);
                intent.putExtra(PopupActivity.POPUP_MODE, PopupActivity.MODE_NORMAL);
                intent.putExtra(PopupActivity.POPUP_TITLE_TEXT, "서비스 준비중입니다.");
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if(findViewById(R.id.layoutInfo).getVisibility() == View.VISIBLE) {
            findViewById(R.id.layoutInfo).setVisibility(View.GONE);
        } else if(findViewById(R.id.layoutMore).getVisibility() == View.VISIBLE) {
            findViewById(R.id.layoutMore).setVisibility(View.GONE);
        } else {
            //super.onBackPressed();
            cancelToExit(this);
        }
    }

    // Initialize this activity
    private void init() {
        // Get the user name
        Bundle extras = getIntent().getExtras();
        username = AppHelper.getCurrUser();
        user = AppHelper.getPool().getUser(username);

        layoutSmartLight = new LinearLayout[]{findViewById(R.id.layoutSmartLight01),findViewById(R.id.layoutSmartLight02),findViewById(R.id.layoutSmartLight03),findViewById(R.id.layoutSmartLight04)};
        imgSmartLightIcon = new ImageView[]{findViewById(R.id.imgIcon01),findViewById(R.id.imgIcon02),findViewById(R.id.imgIcon03),findViewById(R.id.imgIcon04)};
        txtSmartLightName = new TextView[]{findViewById(R.id.txtName01),findViewById(R.id.txtName02),findViewById(R.id.txtName03),findViewById(R.id.txtName04)};
        txtSmartLightGroupName = new TextView[]{findViewById(R.id.txtGroupName01),findViewById(R.id.txtGroupName02),findViewById(R.id.txtGroupName03),findViewById(R.id.txtGroupName04)};
        smartLightPower = new int[]{NOTING,NOTING,NOTING,NOTING};

        //스마트 조명 배경 라운드 처리
        GradientDrawable drawable= (GradientDrawable) getDrawable(R.drawable.layout_round);
        findViewById(R.id.imgSmartLight).setBackground(drawable);
        findViewById(R.id.imgSmartLight).setClipToOutline(true);

        //위치정보
        findViewById(R.id.layoutLocationInfo).setVisibility(View.GONE);
        findViewById(R.id.btnRegisterLocation).setVisibility(View.VISIBLE);

        //디바이스
        findViewById(R.id.layoutRegisterDevice).setVisibility(View.VISIBLE);
        findViewById(R.id.layoutAddHome).setVisibility(View.GONE);
        findViewById(R.id.layoutSmartLight).setVisibility(View.GONE);
        findViewById(R.id.listViewDeviceHome).setVisibility(View.GONE);
        //TODO - 데모코드
        findViewById(R.id.layoutSmartInfo).setVisibility(View.GONE);
        findViewById(R.id.layoutSmartDevice).setVisibility(View.GONE);
        //TODO - 데모코드(스마트 스마트 조명)
        findViewById(R.id.layoutSmartDevice01).setEnabled(false);
        findViewById(R.id.layoutSmartDevice02).setEnabled(false);
    }

    private void setUi() {
        //위치 정보
        if(UserInfo.location.size() == 0) {
            findViewById(R.id.layoutLocationInfo).setVisibility(View.GONE);
            findViewById(R.id.btnRegisterLocation).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.layoutLocationInfo).setVisibility(View.VISIBLE);
            findViewById(R.id.btnRegisterLocation).setVisibility(View.GONE);

            if(!UserInfo.location.get(0).address.city.isEmpty() || !UserInfo.location.get(0).address.district.isEmpty() || !UserInfo.location.get(0).address.town.isEmpty() ) {
                ((TextView)findViewById(R.id.txtAddress)).setText(UserInfo.location.get(0).address.city + " " + UserInfo.location.get(0).address.district +" " + UserInfo.location.get(0).address.town);
            }

            if(UserInfo.weatherInfos.size() > 0) {
                //하늘 상태 * 10 + 강수 형태
                switch ((Integer.valueOf(UserInfo.weatherInfos.get(0).sky)*10) + Integer.valueOf(UserInfo.weatherInfos.get(0).pty)) {
                    case 10: //맑음
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_1_1);
                        break;
                    case 11: //비
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_4);
                        break;
                    case 12: //진눈개비
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_5);
                        break;
                    case 13: //눈
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_6);
                        break;
                    case 14: //소나기
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_4);
                        break;
                    case 15: //빗방울
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_8);
                        break;
                    case 16: //빛방울/눈날림
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_9);
                        break;
                    case 17: //눈날림
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_10);
                        break;
                    case 30: //구름 많음
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_2);
                        break;
                    case 31: //구름 많음 + 비
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_7);
                        break;
                    case 32: //구름 많음 + 진눈개비
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_11);
                        break;
                    case 33: //구름 많음 + 눈
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_12);
                        break;
                    case 34: //구름 많음 + 소나기
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_7);
                        break;
                    case 35: //구름 많음 + 빗방울
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_13);
                        break;
                    case 36: //구름 많음 + 빛방울/눈날림
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_14);
                        break;
                    case 37: //구름 많음 + 눈날림
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_15);
                        break;

                    case 40: //흐림
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_3);
                        break;
                    case 41: //흐림 + 비
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_16);
                        break;
                    case 42: //흐림 + 진눈개비
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_17);
                        break;
                    case 43: //흐림 + 눈
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_18);
                        break;
                    case 44: //흐림 + 소나기
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_16);
                        break;
                    case 45: //흐림 + 빗방울
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_19);
                        break;
                    case 46: //흐림 + 빛방울/눈날림
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_20);
                        break;
                    case 47: //흐림 + 눈날림
                        ((ImageView) findViewById(R.id.imgWeather)).setImageResource(R.drawable.weather_21);
                        break;
                    default://UNKNOWN
                        ((ImageView) findViewById(R.id.imgWeather)).setVisibility(View.INVISIBLE);
                        break;
                }

                //온도
                if(UserInfo.weatherInfos.get(0).t1h.equals("-999")) {
                    ((TextView) findViewById(R.id.txtTemp)).setText("NO DATE");
                } else {
                    ((TextView) findViewById(R.id.txtTemp)).setText(UserInfo.weatherInfos.get(0).t1h);
                }

                //습도
                if(UserInfo.weatherInfos.get(0).reh.equals("-999")) {
                    ((TextView) findViewById(R.id.txtHumi)).setText("NO DATE");
                } else {
                    ((TextView) findViewById(R.id.txtHumi)).setText(UserInfo.weatherInfos.get(0).reh);
                }

                //미세먼지
                try {
                    switch (Integer.valueOf(UserInfo.weatherInfos.get(0).pm10Grade)) {
                        case 1: //좋음
                            ((LinearLayout) findViewById(R.id.layoutFindDust)).setBackgroundResource(R.drawable.background_dust_level_good);
                            break;
                        case 2: //보통
                            ((LinearLayout) findViewById(R.id.layoutFindDust)).setBackgroundResource(R.drawable.background_dust_level_normal);
                            break;
                        case 3: //나쁨
                            ((LinearLayout) findViewById(R.id.layoutFindDust)).setBackgroundResource(R.drawable.background_dust_level_bad);
                            break;
                        case 4: //매우나쁨
                            ((LinearLayout) findViewById(R.id.layoutFindDust)).setBackgroundResource(R.drawable.background_dust_level_very_bad);
                            break;
                        default://UNKNOWN
                            ((LinearLayout) findViewById(R.id.layoutFindDust)).setBackgroundResource(R.drawable.background_dust_level_unknown);
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    //초미세먼지지
                    switch (Integer.valueOf(UserInfo.weatherInfos.get(0).pm25Grade)) {
                        case 1: //좋음
                            ((LinearLayout) findViewById(R.id.layoutUltraFindDust)).setBackgroundResource(R.drawable.background_dust_level_good);
                            break;
                        case 2: //보통
                            ((LinearLayout) findViewById(R.id.layoutUltraFindDust)).setBackgroundResource(R.drawable.background_dust_level_normal);
                            break;
                        case 3: //나쁨
                            ((LinearLayout) findViewById(R.id.layoutUltraFindDust)).setBackgroundResource(R.drawable.background_dust_level_bad);
                            break;
                        case 4: //매우나쁨
                            ((LinearLayout) findViewById(R.id.layoutUltraFindDust)).setBackgroundResource(R.drawable.background_dust_level_very_bad);
                            break;
                        default://UNKNOWN
                            ((LinearLayout) findViewById(R.id.layoutUltraFindDust)).setBackgroundResource(R.drawable.background_dust_level_unknown);
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //업데이트 날짜시간,
                ((TextView)findViewById(R.id.txtWeatherUpdateInfo)).setText(UserInfo.weatherInfos.get(0).adDatetime+"(µg/m2)");
            }
        }

        //디바이스
        if(UserInfo.devicesString.size() > 0) {
            findViewById(R.id.layoutRegisterDevice).setVisibility(View.GONE);
            findViewById(R.id.layoutAddHome).setVisibility(View.GONE);
            findViewById(R.id.layoutSmartLight).setVisibility(View.VISIBLE);
            findViewById(R.id.listViewDeviceHome).setVisibility(View.VISIBLE);
            //TODO - 데모코드
            findViewById(R.id.layoutSmartInfo).setVisibility(View.VISIBLE);
            findViewById(R.id.layoutSmartDevice).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.layoutRegisterDevice).setVisibility(View.VISIBLE);
            findViewById(R.id.layoutAddHome).setVisibility(View.GONE);
            findViewById(R.id.layoutSmartLight).setVisibility(View.GONE);
            findViewById(R.id.listViewDeviceHome).setVisibility(View.GONE);
            //TODO - 데모코드
            findViewById(R.id.layoutSmartInfo).setVisibility(View.GONE);
            findViewById(R.id.layoutSmartDevice).setVisibility(View.GONE);
        }

        getSmartLightAndHome();
    }

    /*
    private void clearUserInfo() {
        UserInfo.location.clear();
        UserInfo.weatherInfos.clear();
        UserInfo.devicesString.clear();
        UserInfo.dgroupsString.clear();
    }
    */

    private void getUserInfo() {

        UserInfo.getUserInfo(this, new UserInfo.CallbackForUpdate() {
            @Override
            public void updateData() {
                //Local DB 스마트 조명과 서버에 등록된 스마트 조명 싱크.
                syncLocalDB();
                //날씨 정보 획득
                if(!UserInfo.confirmed) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sendConfirmEmail(MainActivity.this);
                            //showNotiMsg(MainActivity.this, "인증 후 사용 가능합니다.");
                        }
                    });
                } else if(UserInfo.location.size() == 0) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setUi();
                            if(!UserInfo.isSendPushToken && UserInfo.confirmed) {
                                sendPushToken();
                            }

                            if(!UserInfo.isCheckInvite && UserInfo.confirmed) {
                                checkInvite();
                            }
                        }
                    });
                } else {
                    getWeatherInfo(UserInfo.location.get(0).locationId);
                }
            }
        });

        /*
        clearUserInfo();
        displayProgress(this,null,null);
        try {
            HttpApi.getUserInfo(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    ErrorLogOutput(TAG, "HttpApi.getUserInfo(onFailure) : " + e.toString());
                    DismissConnectDialog();
                    showNotiMsg(MainActivity.this,getString(R.string.snackbar_error_server));
                }

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

                            UserInfo.uid = json_data.isNull("uid") ? "" : json_data.getString("uid");
                            UserInfo.email = json_data.isNull("email") ? "" : json_data.getString("email");
                            UserInfo.phoneNumber = json_data.isNull("phoneNumber") ? "" : json_data.getString("phoneNumber");
                            UserInfo.nickname = json_data.isNull("nickname") ? "" : json_data.getString("nickname");
                            UserInfo.profile = json_data.isNull("profile") ? "" : json_data.getString("profile");
                            UserInfo.confirmed = json_data.isNull("confirmed") ? false : json_data.getBoolean("confirmed");
                            UserInfo.pushAccess = json_data.isNull("pushAccess") ? false : json_data.getBoolean("pushAccess");
                            UserInfo.autoUpdate = json_data.isNull("autoUpdate") ? false : json_data.getBoolean("autoUpdate");

                            if(!json_data.isNull("locations")) {
                                JSONArray jarrayLocationInfo = new JSONArray(json_data.getString("locations"));
                                for (int i = 0; i < jarrayLocationInfo.length(); i++) {
                                    JSONObject jObjectLocationInfo = jarrayLocationInfo.getJSONObject(i);
                                    LocationInfo locationInfo = new LocationInfo();

                                    locationInfo.locationId = jObjectLocationInfo.isNull("locationId") ? "" : jObjectLocationInfo.getString("locationId");
                                    locationInfo.latitude = jObjectLocationInfo.isNull("latitude") ? 0 : jObjectLocationInfo.getDouble("latitude");
                                    locationInfo.longitude = jObjectLocationInfo.isNull("longitude") ? 0 : jObjectLocationInfo.getDouble("longitude");

                                    if (!jObjectLocationInfo.isNull("address")) {
                                        JSONObject jObjectAddressInfo = new JSONObject(jObjectLocationInfo.getString("address"));

                                        locationInfo.address.city = jObjectAddressInfo.isNull("city") ? "" : jObjectAddressInfo.getString("city");
                                        locationInfo.address.district = jObjectAddressInfo.isNull("district") ? "" : jObjectAddressInfo.getString("district");
                                        locationInfo.address.town = jObjectAddressInfo.isNull("town") ? "" : jObjectAddressInfo.getString("town");
                                    }
                                    UserInfo.location.add(locationInfo);
                                }
                            }

                            if(!json_data.isNull("dgroups")) {
                                JSONObject jObjectDgroupInfo = new JSONObject(json_data.getString("dgroups"));
                                if(!jObjectDgroupInfo.isNull("results")) {
                                    JSONArray arrJson = jObjectDgroupInfo.getJSONArray("results");
                                    for (int i = 0; i < arrJson.length(); i++) {
                                        UserInfo.dgroupsString.add(arrJson.getString(i));
                                    }
                                }

                                UserInfo.dgroupsCount = jObjectDgroupInfo.isNull("count")?0:jObjectDgroupInfo.getInt("count");
                            }

                            if(!json_data.isNull("devices")) {
                                JSONObject jObjectDeviceInfo = new JSONObject(json_data.getString("devices"));
                                if(!jObjectDeviceInfo.isNull("results")) {
                                    JSONArray arrJson = jObjectDeviceInfo.getJSONArray("results");
                                    for (int i = 0; i < arrJson.length(); i++) {
                                        UserInfo.devicesString.add(arrJson.getString(i));
                                    }
                                }
                                UserInfo.deviceCount = jObjectDeviceInfo.isNull("count")?0:jObjectDeviceInfo.getInt("count");
                            }

                            //날씨 정보 획득
                            if(!UserInfo.confirmed) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        showNotiMsg(MainActivity.this, "인증 후 사용 가능합니다.");
                                        DismissConnectDialog();
                                    }
                                });
                            } else if(UserInfo.location.size() == 0) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        setUi();
                                        DismissConnectDialog();

                                        if(!UserInfo.isSendPushToken && UserInfo.confirmed) {
                                            sendPushToken();
                                        }

                                        if(!UserInfo.isCheckInvite && UserInfo.confirmed) {
                                            checkInvite();
                                        }
                                    }
                                });
                            } else {
                                getWeatherInfo(UserInfo.location.get(0).locationId);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.getUserInfo(JSONException)\n" + e.toString());
                            DismissConnectDialog();
                            showNotiMsg(MainActivity.this,getString(R.string.snackbar_error_server));
                        }
                    } else {
                        ErrorLogOutput(TAG, "HttpApi.getUserInfo(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                        showNotiMsg(MainActivity.this,getString(R.string.snackbar_error_server));
                        DismissConnectDialog();
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            ErrorLogOutput(TAG, "HttpApi.getUserInfo(onResponse) body : " + json_data.toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.getUserInfo(onResponse) JSONException : " + e.toString());
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.getUserInfo(Exception) : " + e.toString());
            showNotiMsg(MainActivity.this,getString(R.string.snackbar_error_server));
            DismissConnectDialog();
        }
         */
    }

    private void getWeatherInfo(final String locationId) {
        UserInfo.getWeatherInfo(MainActivity.this, locationId, new UserInfo.CallbackForUpdate() {
            @Override
            public void updateData() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setUi();
                        DismissConnectDialog();

                        if(!UserInfo.isSendPushToken && UserInfo.confirmed) {
                            sendPushToken();
                        }

                        if(!UserInfo.isCheckInvite && UserInfo.confirmed) {
                            checkInvite();
                        }
                    }
                });
            }
        });

        /*
        UserInfo.weatherInfos.clear();
        try {
            HttpApi.getWeatherInfo(locationId, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    ErrorLogOutput(TAG, "HttpApi.getWeatherInfo(onFailure) : " + e.toString());
                    showNotiMsg(MainActivity.this,getString(R.string.snackbar_error_server));

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setUi();
                            DismissConnectDialog();

                            if(!UserInfo.isSendPushToken && UserInfo.confirmed) {
                                sendPushToken();
                            }

                            if(!UserInfo.isCheckInvite && UserInfo.confirmed) {
                                checkInvite();
                            }
                        }
                    });
                }

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

                            WeatherInfo weatherInfo = new WeatherInfo();

                            weatherInfo.o3Value = json_data.isNull("o3Value") ? "-1" : json_data.getString("o3Value");
                            weatherInfo.o3Grad = json_data.isNull("o3Grad") ? "-1" : json_data.getString("o3Grad");
                            weatherInfo.pm10Value = json_data.isNull("pm10Value") ? "-1" : json_data.getString("pm10Value");
                            weatherInfo.pm10Grade = json_data.isNull("pm10Grade") ? "-1" : json_data.getString("pm10Grade");
                            weatherInfo.pm25Value = json_data.isNull("pm25Value") ? "-1" : json_data.getString("pm25Value");
                            weatherInfo.pm25Grade = json_data.isNull("pm25Grade") ? "-1" : json_data.getString("pm25Grade");
                            weatherInfo.adDatetime = json_data.isNull("adDatetime") ? "-1" : json_data.getString("adDatetime");

                            weatherInfo.sky = json_data.isNull("sky") ? "-1" : json_data.getString("sky");
                            weatherInfo.pty = json_data.isNull("pty") ? "-1" : json_data.getString("pty");
                            weatherInfo.rn1 = json_data.isNull("rn1") ? "-1" : json_data.getString("rn1");
                            weatherInfo.reh = json_data.isNull("reh") ? "-999" : json_data.getString("reh");
                            weatherInfo.t1h = json_data.isNull("t1h") ? "-999" : json_data.getString("t1h");
                            weatherInfo.wdDatetime = json_data.isNull("wdDatetime") ? "" : json_data.getString("wdDatetime");

                            UserInfo.weatherInfos.add(weatherInfo);

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    setUi();
                                    DismissConnectDialog();

                                    if(!UserInfo.isSendPushToken && UserInfo.confirmed) {
                                        sendPushToken();
                                    }

                                    if(!UserInfo.isCheckInvite && UserInfo.confirmed) {
                                        checkInvite();
                                    }
                                }
                            });

                        } catch (JSONException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.getWeatherInfo(JSONException)\n" + e.toString());
                            DismissConnectDialog();
                            showNotiMsg(MainActivity.this,getString(R.string.snackbar_error_server));

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    setUi();
                                    DismissConnectDialog();

                                    if(!UserInfo.isSendPushToken && UserInfo.confirmed) {
                                        sendPushToken();
                                    }

                                    if(!UserInfo.isCheckInvite && UserInfo.confirmed) {
                                        checkInvite();
                                    }
                                }
                            });
                        }
                    } else {
                        ErrorLogOutput(TAG, "HttpApi.getWeatherInfo(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                        showNotiMsg(MainActivity.this,getString(R.string.snackbar_error_server));
                        DismissConnectDialog();
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            ErrorLogOutput(TAG, "HttpApi.getWeatherInfo(onResponse) body : " + json_data.toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.getWeatherInfo(onResponse) JSONException : " + e.toString());
                        }

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                setUi();
                                DismissConnectDialog();

                                if(!UserInfo.isSendPushToken && UserInfo.confirmed) {
                                    sendPushToken();
                                }

                                if(!UserInfo.isCheckInvite && UserInfo.confirmed) {
                                    checkInvite();
                                }
                            }
                        });
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.getWeatherInfo(Exception) : " + e.toString());
            showNotiMsg(MainActivity.this,getString(R.string.snackbar_error_server));
            DismissConnectDialog();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setUi();
                    DismissConnectDialog();

                    if(!UserInfo.isSendPushToken && UserInfo.confirmed) {
                        sendPushToken();
                    }

                    if(!UserInfo.isCheckInvite && UserInfo.confirmed) {
                        checkInvite();
                    }
                }
            });
        }
         */
    }

    private void syncLocalDB() {
        smartLights = DBUtil.getAllDeviceInfos(TABLE_SMART_LIGHT);
        homeDevices = DBUtil.getAllDeviceInfos(TABLE_DEVICE_HOME);
        rankDevices = DBUtil.getAllDeviceInfos(TABLE_DEVICE_RANK);

        //디바이스 서버와 로컬 유무 체크.(스마트 조명)
        for(int i = 0 ; i < smartLights.size() ; i++) {
            boolean isExsit = false;
            for(int j = 0 ; j < UserInfo.devicesString.size() ; j++) {
                if(smartLights.get(i).deviceId.equals(UserInfo.devicesString.get(j))){
                    isExsit = true;
                }
            }
            if(!isExsit && smartLights.get(i).sharedFriendlyName.isEmpty()) {
                DBUtil.removeDeviceInfo(TABLE_SMART_LIGHT,smartLights.get(i));
                smartLights.remove(i);
                i--;
            }
        }

        //디바이스 서버와 로컬 유무 체크.(즐겨찾기 홈)
        for(int i = 0 ; i < homeDevices.size() ; i++) {
            boolean isExsit = false;
            for(int j = 0 ; j < UserInfo.devicesString.size() ; j++) {
                if(homeDevices.get(i).deviceId.equals(UserInfo.devicesString.get(j))){
                    isExsit = true;
                }
            }
            if(!isExsit && homeDevices.get(i).sharedFriendlyName.isEmpty()) {
                DBUtil.removeDeviceInfo(TABLE_DEVICE_HOME,homeDevices.get(i));
                homeDevices.remove(i);
                i--;
            }
        }

        //디바이스 서버와 로컬 유무 체크.(스마트 조명 순서)
        for(int i = 0 ; i < rankDevices.size() ; i++) {
            boolean isExsit = false;
            for(int j = 0 ; j < UserInfo.devicesString.size() ; j++) {
                if(rankDevices.get(i).deviceId.equals(UserInfo.devicesString.get(j))){
                    isExsit = true;
                }
            }
            if(!isExsit && rankDevices.get(i).sharedFriendlyName.isEmpty()) {
                DBUtil.removeDeviceInfo(TABLE_DEVICE_RANK,rankDevices.get(i));
                rankDevices.remove(i);
                i--;
            }
        }
    }

    private void getSmartLightAndHome() {
        smartLights = DBUtil.getAllDeviceInfos(TABLE_SMART_LIGHT);
        homeDevices = DBUtil.getAllDeviceInfos(TABLE_DEVICE_HOME);
        rankDevices = DBUtil.getAllDeviceInfos(TABLE_DEVICE_RANK);

        if (UserInfo.deviceCount == 0 && smartLights.size() == 0 && homeDevices.size() ==0) {
            findViewById(R.id.layoutRegisterDevice).setVisibility(View.VISIBLE);
            findViewById(R.id.layoutAddHome).setVisibility(View.GONE);
            findViewById(R.id.layoutSmartLight).setVisibility(View.GONE);
            findViewById(R.id.listViewDeviceHome).setVisibility(View.GONE);
            //TODO - 데모코드
            findViewById(R.id.layoutSmartInfo).setVisibility(View.GONE);
            findViewById(R.id.layoutSmartDevice).setVisibility(View.GONE);
        } else {
            if(smartLights.size() == 0 && homeDevices.size() ==0) {
                findViewById(R.id.layoutRegisterDevice).setVisibility(View.GONE);
                findViewById(R.id.layoutAddHome).setVisibility(View.VISIBLE);
                findViewById(R.id.layoutSmartLight).setVisibility(View.GONE);
                findViewById(R.id.listViewDeviceHome).setVisibility(View.GONE);
                //TODO - 데모코드
                findViewById(R.id.layoutSmartInfo).setVisibility(View.GONE);
                findViewById(R.id.layoutSmartDevice).setVisibility(View.GONE);
            } else {
                findViewById(R.id.layoutRegisterDevice).setVisibility(View.GONE);
                findViewById(R.id.layoutAddHome).setVisibility(View.GONE);

                if(smartLights.size() > 0) {
                    findViewById(R.id.layoutSmartLight).setVisibility(View.VISIBLE);
                    //TODO - 데모코드
                    findViewById(R.id.layoutSmartInfo).setVisibility(View.VISIBLE);
                    findViewById(R.id.layoutSmartDevice).setVisibility(View.VISIBLE);

                    for (int i = 0; i < layoutSmartLight.length; i++) {
                        layoutSmartLight[i].setVisibility(View.INVISIBLE);
                        layoutSmartLight[i].setEnabled(false);
                    }

                    for (int i = 0; (i < smartLights.size()) && (i < layoutSmartLight.length); i++) {
                        final int pos = i;
                        layoutSmartLight[i].setVisibility(View.VISIBLE);
                        layoutSmartLight[i].setEnabled(false);
                        txtSmartLightName[i].setText(smartLights.get(i).friendlyName.isEmpty()?smartLights.get(i).sharedFriendlyName.isEmpty()?getString(R.string.no_name):smartLights.get(i).sharedFriendlyName:smartLights.get(i).friendlyName);
                        txtSmartLightGroupName[i].setText(smartLights.get(i).dgroupName);

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

                        layoutSmartLight[i].setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if(smartLightPower[pos] == NOTING) {
                                    showNotiMsg(MainActivity.this,"조명이 연결되지 않았습니다.");
                                } else if(smartLightPower[pos] == POWER_ON) { //켜진상태
                                    MqttController.getInstance().publish(topicUpdateP,"{\"state\": {\"desired\" : {\"power\" : 0}}}");
                                    layoutSmartLight[pos].setSelected(false);
                                } else /*if(power == POWER_OFF)*/ { //꺼진상태
                                    MqttController.getInstance().publish(topicUpdateP,"{\"state\": {\"desired\" : {\"power\" : 1}}}");
                                    layoutSmartLight[pos].setSelected(true);
                                }
                            }
                        });

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

                                int temp_power = NOTING;

                                try {
                                    JSONObject jsonObject = new JSONObject(new String(data));

                                    if(!jsonObject.isNull("data")) {//Get status topic
                                        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");

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

                                final int powerFix = temp_power;

                                if(temp_power != NOTING) {
                                    smartLightPower[pos] = temp_power;
                                }

                                DebugLogOutput(TAG, "LIGHT_STATUS - power : "+powerFix);

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if(smartLightPower[pos] == NOTING) {
                                            layoutSmartLight[pos].setEnabled(false);
                                            layoutSmartLight[pos].setSelected(false);
                                        } else if(smartLightPower[pos] == POWER_ON) {
                                            imgSmartLightIcon[pos].setImageResource(R.drawable.icon_home_device_light);
                                            layoutSmartLight[pos].setEnabled(true);
                                            layoutSmartLight[pos].setSelected(true);
                                        } else if(smartLightPower[pos] == POWER_OFF) {
                                            imgSmartLightIcon[pos].setImageResource(R.drawable.icon_home_device_light);
                                            layoutSmartLight[pos].setEnabled(true);
                                            layoutSmartLight[pos].setSelected(false);
                                        }
                                    }
                                });
                            }
                        });

                        MqttController.getInstance().subscribeToTopic(topicUpdateS1, 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("data")) {//Get status topic
                                        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");

                                            }
                                        }
                                    } 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");

                                            }
                                        }

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

                                            }
                                        }

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

                                final int powerFix = temp_power;

                                if(temp_power != NOTING) {
                                    smartLightPower[pos] = temp_power;
                                }

                                DebugLogOutput(TAG, "LIGHT_STATUS - power : "+powerFix);

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if(smartLightPower[pos] == NOTING) {
                                            layoutSmartLight[pos].setEnabled(false);
                                            layoutSmartLight[pos].setSelected(false);
                                        } else if(smartLightPower[pos] == POWER_ON) {
                                            layoutSmartLight[pos].setEnabled(true);
                                            layoutSmartLight[pos].setSelected(true);
                                        } else if(smartLightPower[pos] == POWER_OFF) {
                                            layoutSmartLight[pos].setEnabled(true);
                                            layoutSmartLight[pos].setSelected(false);
                                        }
                                    }
                                });
                            }
                        });

                        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() {
                                if(smartLights != null && smartLights.size() > pos) {

                                    MqttController.getInstance().publish(topicGetP, "{\"msgId\" : \"" + UUID.randomUUID().toString() + "\"}");
                                    //MqttController.getInstance().publish(topicGetP, "{\"msgId\" : \"" + smartLights.get(pos).deviceId + "\"}");
                                }
                            }
                        },MQTT_PUBLISH_DELAY_TIME);
                    }
                } else {
                    findViewById(R.id.layoutSmartLight).setVisibility(View.GONE);
                    //TODO - 데모코드
                    findViewById(R.id.layoutSmartInfo).setVisibility(View.GONE);
                    findViewById(R.id.layoutSmartDevice).setVisibility(View.GONE);
                }

                if(homeDevices.size() > 0) {
                    findViewById(R.id.listViewDeviceHome).setVisibility(View.VISIBLE);
                    ListView listView = findViewById(R.id.listViewDeviceHome);
                    DeviceListAdapter deviceListAdapter = new DeviceListAdapter(this, homeDevices);
                    listView.setAdapter(deviceListAdapter);
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            final DeviceInfo item = (DeviceInfo) parent.getItemAtPosition(position);
                            Intent intent = new Intent(MainActivity.this,LightDetailActivity.class);
                            intent.putExtra(EXTRA_DEVICE_INFO, (Parcelable) item);
                            startActivity(intent);
                        }
                    });
                } else {
                    findViewById(R.id.listViewDeviceHome).setVisibility(View.GONE);
                }
            }
        }
    }

    private void sendPushToken() {
        final String pushToken = SharedPrefUtil.getString(SharedPrefUtil.PUSH_TOKEN,SharedPrefUtil.DEFAULT_PUSH_TOKEN);
        if(!pushToken.isEmpty()) {
            try {
                HttpApi.changeUserInfo("", "", "", UserInfo.pushAccess, UserInfo.autoUpdate, pushToken, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        ErrorLogOutput(TAG, "HttpApi.changeUserInfo(onFailure)\n" + e.toString());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (response.code() == HttpApi.HTTP_NO_CONTENT) {
                            WarnLogOutput(TAG, "HttpApi.changeUserInfo(onResponse) HTTP_NO_CONTENT");
                            UserInfo.isSendPushToken = true;
                        } else {
                            ErrorLogOutput(TAG, "HttpApi.changeUserInfo(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                            try {
                                JSONObject json_data = new JSONObject(response.body().string());
                                ErrorLogOutput(TAG, "HttpApi.changeUserInfo(onResponse) body : " + json_data.toString());
                            } catch (JSONException e) {
                                ErrorLogOutput(TAG, "HttpApi.changeUserInfo(onResponse) JSONException : " + e.toString());
                            }
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                ErrorLogOutput(TAG, "HttpApi.changeUserInfo(Exception)\n" + e.toString());
            }
        }
    }


    private void checkInvite() {

        if(InviteInfos == null) {
            InviteInfos = new ArrayList<>();
        } else {
            InviteInfos.clear();
        }

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

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

                        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);
                                InviteInfo item = new InviteInfo(
                                        jObject.isNull("histId") ? "" : jObject.getString("histId"),
                                        jObject.isNull("inviteType") ? "" : jObject.getString("inviteType"),
                                        jObject.isNull("sender") ? "" : jObject.getString("sender"),
                                        jObject.isNull("target") ? "" : jObject.getString("target"),
                                        jObject.isNull("inviteDate") ? "" : jObject.getString("inviteDate"),
                                        jObject.isNull("expireDate") ? "" : jObject.getString("expireDate"));

                                SimpleDateFormat transFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                                Date expireDate = transFormat.parse(item.expireDate);

                                if(System.currentTimeMillis() < expireDate.getTime()) {
                                    InviteInfos.add(item);
                                }
                            }

                            if(InviteInfos.size() > 0) {
                                Intent intent = new Intent(MainActivity.this, PopupActivity.class);
                                intent.putExtra(PopupActivity.POPUP_MODE,PopupActivity.MODE_YESNO);
                                intent.putExtra(PopupActivity.POPUP_BODY_TEXT,String.format(getString(R.string.popup_invite_you),InviteInfos.get(0).sender));
                                intent.putExtra(PopupActivity.POPUP_CANCEL_BUTTON_TEXT,getString(R.string.reject));
                                intent.putExtra(PopupActivity.POPUP_OK_BUTTON_TEXT,getString(R.string.accept));
                                startActivityForResult(intent,RESULT_INVITE_CONFIRM);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.getHistoryForInvite(JSONException)\n" + e.toString());
                        } catch (ParseException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.getHistoryForInvite(ParseException)\n" + e.toString());
                        }


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

    private void comfirmInvite(final boolean yes) {
        try {
            HttpApi.acceptToInvite(InviteInfos.get(0).histId, yes, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    ErrorLogOutput(TAG, "HttpApi.acceptToInvite(onFailure)\n" + e.toString());

                    if(yes) {
                        showNotiMsg(MainActivity.this, "수락을 하지못하였습니다.");
                    } else {
                        showNotiMsg(MainActivity.this, "거절을 하지못하였습니다.");
                    }
                }

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

                        if(yes) {
                            showNotiMsg(MainActivity.this, "수락 하였습니다.");
                        } else {
                            showNotiMsg(MainActivity.this, "거절 하였습니다.");
                        }

                        InviteInfos.remove(0);
                        if(InviteInfos.size() > 0) {
                            Intent intent = new Intent(MainActivity.this, PopupActivity.class);
                            intent.putExtra(PopupActivity.POPUP_MODE,PopupActivity.MODE_YESNO);
                            intent.putExtra(PopupActivity.POPUP_BODY_TEXT,String.format(getString(R.string.popup_invite_you),InviteInfos.get(0).sender));
                            intent.putExtra(PopupActivity.POPUP_CANCEL_BUTTON_TEXT,getString(R.string.reject));
                            intent.putExtra(PopupActivity.POPUP_OK_BUTTON_TEXT,getString(R.string.accept));
                            startActivityForResult(intent,RESULT_INVITE_CONFIRM);
                        }

                    } else {
                        ErrorLogOutput(TAG, "HttpApi.acceptToInvite(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                        if(yes) {
                            showNotiMsg(MainActivity.this, "수락을 하지못하였습니다.");
                        } else {
                            showNotiMsg(MainActivity.this, "거절을 하지못하였습니다.");
                        }
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            ErrorLogOutput(TAG, "HttpApi.acceptToInvite(onResponse) body : " + json_data.toString());
                        } catch (JSONException e) {
                            ErrorLogOutput(TAG, "HttpApi.acceptToInvite(onResponse) JSONException : " + e.toString());
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.acceptToInvite(Exception)\n" + e.toString());
            if(yes) {
                showNotiMsg(MainActivity.this, "수락을 하지못하였습니다.");
            } else {
                showNotiMsg(MainActivity.this, "거절을 하지못하였습니다.");
            }
        }
    }

    private void exit () {
        Intent intent = new Intent();
        if(username == null)
            username = "";
        intent.putExtra("name",username);
        setResult(RESULT_OK, intent);
        finish();
    }
}