package kr.co.icontrols.iotplatform;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.material.tabs.TabLayout;

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.adapter.DeviceListAdapter;
import kr.co.icontrols.iotplatform.adapter.MyGroupTabPagerAdapter;
import kr.co.icontrols.iotplatform.utils.GetSessionCallback;
import kr.co.icontrols.iotplatform.utils.HttpApi;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.amazonaws.mobile.auth.core.internal.util.ThreadUtils.runOnUiThread;
import static kr.co.icontrols.iotplatform.Database.DatabaseHelper.TABLE_DEVICE_RANK;
import static kr.co.icontrols.iotplatform.PopupActivity.POPUP_BUNDLE;
import static kr.co.icontrols.iotplatform.PopupActivity.POPUP_IMG_INDEX;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.DismissConnectDialog;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.ErrorLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.ForceDismissConnectDialog;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.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.getGroupBackgroundString;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.getGroupImageString;
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.resetBackgroundWaitTime;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.restartApp;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.setBackgroundWaitTime;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.showNotiMsg;
import static kr.co.icontrols.iotplatform.utils.Constants.DEFAULT_RANK;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_BEFORE_ACTIVITY;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_DEVICE_ID;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_DEVICE_LIST;
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.EXTRA_GROUP_NAME;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_CHANGE_GROUP_IMG;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_INPUT_GROUP_NAME;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_UPDATE_DATA;
import static kr.co.icontrols.iotplatform.utils.HttpApi.HTTP_OK;
import static kr.co.icontrols.iotplatform.utils.HttpApi.HTTP_UNAUTHORIZED;

public class MyGroupActivity extends AppCompatActivity implements View.OnClickListener {
    private final String TAG = "MyGroupActivity";
    private TabLayout mTabGroup;
    private ViewPager mViewPager;
    final ArrayList<DeviceInfo> deviceInfoList = new ArrayList<>();
    private Handler mConnectedHandler;

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

        mTabGroup = findViewById(R.id.tabGroup);
        mViewPager = findViewById(R.id.viewPager);

        if(!UserInfo.confirmed) {
            showNotiMsg(this, "인증 후 사용 가능합니다.");
        } else if(isExpiredSession()) {
            getCognitoSession(new GetSessionCallback() {
                @Override
                public void successed() {
                    getMyDeviceGroup();
                }

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

        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()) {
                    if(mViewPager.getAdapter() != null) {
                        MqttController.getInstance().allUnsubscribeToTopics();
                        ((MyGroupTabPagerAdapter) mViewPager.getAdapter()).notifyDataSetChanged();
                    }
                } else {
                    mConnectedHandler.sendEmptyMessageDelayed(1,1000);
                }
            }
        };
    }

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

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

        if(mViewPager.getAdapter() != null) {
            MqttController.getInstance().allUnsubscribeToTopics();
            ((MyGroupTabPagerAdapter) mViewPager.getAdapter()).notifyDataSetChanged();

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

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

    @Override
    protected void onDestroy() {
        resetBackgroundWaitTime();
        if(deviceInfoList != null) {
            deviceInfoList.clear();
        }
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_INPUT_GROUP_NAME:
                if (resultCode == RESULT_OK) {
                    Bundle b = data.getBundleExtra(POPUP_BUNDLE);
                    if(b != null) {
                        try {
                            String newValue = b.getString(PopupActivity.POPUP_INPUT);
                            if(!newValue.equals(UserInfo.dgroups.get(mViewPager.getCurrentItem()).friendlyName)) {
                                changeGroup(newValue,"","");
                            }
                        } catch (Exception e) {
                            // Log failure
                            showNotiMsg(MyGroupActivity.this,getString(R.string.snackbar_fail_change_group));
                        }
                    } else {
                        showNotiMsg(MyGroupActivity.this,getString(R.string.snackbar_fail_change_group));
                    }
                }
                break;
            case RESULT_CHANGE_GROUP_IMG:
                if (resultCode == RESULT_OK) {
                    final int selected_index = data.getIntExtra(POPUP_IMG_INDEX, 1);
                    changeGroup("",getGroupImageString(selected_index),getGroupBackgroundString(selected_index));
                }
                break;
            case RESULT_UPDATE_DATA:
                if (resultCode == RESULT_OK) {

                }
                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:
                onBackPressed();
                break;
            case R.id.btnRight:
                findViewById(R.id.layoutMore).setVisibility(View.VISIBLE);
                break;
            case R.id.btnCloseMore:
                findViewById(R.id.layoutMore).setVisibility(View.GONE);
                break;
            case R.id.btnAddGroup:
            case R.id.layoutMoreAdd: {
                Intent intent = new Intent(this, AddGroupActivity.class);
                intent.putExtra(EXTRA_GROUP_LIST, UserInfo.dgroups);
                intent.putExtra(EXTRA_BEFORE_ACTIVITY,"MyGroupActivity");
                startActivity(intent);
                findViewById(R.id.layoutMore).setVisibility(View.GONE);
                }
                break;
            case R.id.layoutMoreRank:
                if(UserInfo.dgroups.size() > 1) {
                    Intent intent = new Intent(MyGroupActivity.this, GroupChangeRankActivity.class);
                    intent.putExtra(EXTRA_GROUP_LIST, UserInfo.dgroups);
                    startActivity(intent);
                } else {
                    showNotiMsg(MyGroupActivity.this,getString(R.string.snackbar_error_not_found_group_for_changing));
                }
                findViewById(R.id.layoutMore).setVisibility(View.GONE);
                break;
            case R.id.layoutMoreDelete:
                if(UserInfo.dgroups.size() > 1) {
                    UserInfo.setUnSelectAllGroups();
                    Intent intent = new Intent(MyGroupActivity.this, GroupSelectActivity.class);
                    intent.putExtra(EXTRA_GROUP_LIST, UserInfo.dgroups);
                    intent.putExtra("MODE","DELETE");
                    startActivity(intent);
                } else {
                    showNotiMsg(MyGroupActivity.this,getString(R.string.snackbar_error_not_found_group_for_deleting));
                }
                findViewById(R.id.layoutMore).setVisibility(View.GONE);
                break;
            case R.id.btnCloseGroupSetting:
                findViewById(R.id.layoutGroupSetting).setVisibility(View.GONE);
                break;
            case R.id.layoutGroupSettingAdd:
                findViewById(R.id.layoutGroupSetting).setVisibility(View.GONE);
                goToAddDeviceForGroup();
                break;
            case R.id.layoutGroupSettingRank:
                displayProgress(this, "","");
                deviceInfoList.clear();
                try{
                    HttpApi.getDeviceListInDeviceGroup(UserInfo.dgroups.get(mViewPager.getCurrentItem()).dgroupId, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.getDeviceListInDeviceGroup(onFailure)\n" + e.toString());
                            showNotiMsg(MyGroupActivity.this,"순서 변경에 실패하였습니다.");
                            DismissConnectDialog();
                        }

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

                                    for (int i = 0; i < jarrayAll.length(); i++) {
                                        JSONObject jObject = jarrayAll.getJSONObject(i);
                                        DeviceInfo item = new DeviceInfo(
                                                jObject.isNull("deviceId") ? "" : jObject.getString("deviceId"),
                                                jObject.isNull("deviceType") ? "" : jObject.getString("deviceType"),
                                                jObject.isNull("friendlyName") ? "" : jObject.getString("friendlyName"),
                                                jObject.isNull("sharedFriendlyName") ? "" : jObject.getString("sharedFriendlyName"),
                                                jObject.isNull("dgroupId") ? "" : jObject.getString("dgroupId"),
                                                jObject.isNull("dgroupName") ? "" : jObject.getString("dgroupName"),
                                                jObject.isNull("ownerId") ? "" : jObject.getString("ownerId"),
                                                DEFAULT_RANK,
                                                DEFAULT_RANK
                                        );

                                        DeviceInfo localDbItem = DBUtil.getDeviceInfoForId(TABLE_DEVICE_RANK, item.deviceId);
                                        if (localDbItem != null) {
                                            item.rank = localDbItem.rank;
                                            item.groupRank = localDbItem.groupRank;
                                        }

                                        deviceInfoList.add(item);
                                    }

                                    if(deviceInfoList.size() > 1) {
                                        for(int i = 0 ; i < deviceInfoList.size()-1 ; i ++) {
                                            for(int j = i+1 ; j < deviceInfoList.size() ; j ++) {
                                                if(deviceInfoList.get(i).groupRank > deviceInfoList.get(j).groupRank) {
                                                    DeviceInfo item = deviceInfoList.get(j);
                                                    deviceInfoList.remove(j);
                                                    deviceInfoList.add(i,item);
                                                }
                                            }
                                        }

                                        Intent intent = new Intent(MyGroupActivity.this, DeviceChangeRankActivity.class);
                                        intent.putExtra(EXTRA_DEVICE_LIST, deviceInfoList);
                                        intent.putExtra("MODE","GROUP_RANK");
                                        startActivityForResult(intent,RESULT_UPDATE_DATA);
                                    } else {
                                        showNotiMsg(MyGroupActivity.this,"순서 변경할 스마트 조명이 존재하지 않습니다.");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    ErrorLogOutput(TAG, "HttpApi.getDeviceListInDeviceGroup(JSONException)\n" + e.toString());
                                    showNotiMsg(MyGroupActivity.this,"순서 변경에 실패하였습니다.");
                                    DismissConnectDialog();
                                }
                            } else if(response.code() == HTTP_UNAUTHORIZED) {
                                showNotiMsg(MyGroupActivity.this, getString(R.string.snackbar_expired_token));
                                restartApp(MyGroupActivity.this);
                            } else {
                                ErrorLogOutput(TAG, "HttpApi.getDeviceListInDeviceGroup(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                try {
                                    JSONObject json_data = new JSONObject(response.body().string());
                                    ErrorLogOutput(TAG, "HttpApi.getDeviceListInDeviceGroup(onResponse) body : " + json_data.toString());
                                } catch (JSONException e) {
                                    ErrorLogOutput(TAG, "HttpApi.getDeviceListInDeviceGroup(onResponse) JSONException : " + e.toString());
                                }
                                showNotiMsg(MyGroupActivity.this,"순서 변경에 실패하였습니다.");
                                DismissConnectDialog();
                            }
                        }
                    });
                } catch(Exception e){
                    e.printStackTrace();
                    ErrorLogOutput(TAG, "HttpApi.getDeviceListInDeviceGroup(Exception)\n" + e.toString());
                    DismissConnectDialog();
                }
                findViewById(R.id.layoutGroupSetting).setVisibility(View.GONE);
                break;
            case R.id.layoutGroupSettingMove:
                findViewById(R.id.layoutGroupSetting).setVisibility(View.GONE);
                break;
        }
    }

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

    private void showSettingMenu() {
        ((TextView)findViewById(R.id.txtGroupSettingTitle)).setText(UserInfo.dgroups.get(mViewPager.getCurrentItem()).friendlyName+" "+getString(R.string.edit));
        findViewById(R.id.layoutGroupSetting).setVisibility(View.VISIBLE);
    }

    private void goToAddDeviceForGroup() {
        UserInfo.getDevice(this, new UserInfo.CallbackForUpdate() {
            @Override
            public void updateData() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        UserInfo.setUnSelectAllDevices();
                        Intent intent = new Intent(MyGroupActivity.this, DeviceSelectActivity.class);
                        intent.putExtra("MODE", "MOVE_GROUP");
                        intent.putExtra(EXTRA_DEVICE_LIST, UserInfo.devices);
                        intent.putExtra(EXTRA_GROUP_ID, UserInfo.dgroups.get(mViewPager.getCurrentItem()).dgroupId);
                        intent.putExtra(EXTRA_GROUP_NAME, UserInfo.dgroups.get(mViewPager.getCurrentItem()).friendlyName);
                        startActivityForResult(intent,RESULT_UPDATE_DATA);
                    }
                });
            }
        });

        /*
        if(UserInfo.devices.size() > 0) {
            Intent intent = new Intent(MyGroupActivity.this, DeviceSelectActivity.class);
            intent.putExtra("MODE", "MOVE_GROUP");
            intent.putExtra(EXTRA_DEVICE_LIST, UserInfo.devices);
            intent.putExtra(EXTRA_GROUP_ID, UserInfo.dgroups.get(mViewPager.getCurrentItem()).dgroupId);
            intent.putExtra(EXTRA_GROUP_NAME, UserInfo.dgroups.get(mViewPager.getCurrentItem()).friendlyName);
            startActivityForResult(intent,RESULT_UPDATE_DATA);
        } else {
            UserInfo.devices.clear();
            displayProgress(this, null,null);
            try{
                HttpApi.getAllDevice(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        ErrorLogOutput(TAG, "HttpApi.getAllDevice(onFailure)\n" + e.toString());
                        DismissConnectDialog();
                    }

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

                                UserInfo.deviceCount = json_data.isNull("count") ? 0 : json_data.getInt("count");

                                if(UserInfo.deviceCount > 0) {
                                    JSONArray jarrayAll = new JSONArray(json_data.getString("results"));
                                    for (int i = 0; i < jarrayAll.length(); i++) {
                                        JSONObject jObject = jarrayAll.getJSONObject(i);
                                        DeviceInfo item = new DeviceInfo(
                                                jObject.isNull("deviceId") ? "" : jObject.getString("deviceId"),
                                                jObject.isNull("deviceType") ? "" : jObject.getString("deviceType"),
                                                jObject.isNull("friendlyName") ? "" : jObject.getString("friendlyName"),
                                                jObject.isNull("sharedFriendlyName") ? "" : jObject.getString("sharedFriendlyName"),
                                                jObject.isNull("dgroupId") ? "" : jObject.getString("dgroupId"),
                                                jObject.isNull("dgroupName") ? "" : jObject.getString("dgroupName"),
                                                jObject.isNull("ownerId") ? "" : jObject.getString("ownerId"),
                                                DEFAULT_RANK
                                        );

                                        DeviceInfo localDbItem = DBUtil.getDeviceInfoForId(TABLE_DEVICE_RANK, item.deviceId);
                                        if (localDbItem == null) {
                                            DBUtil.putDeviceInfo(TABLE_DEVICE_RANK, item);
                                        } else {
                                            item.rank = localDbItem.rank;
                                            DBUtil.updateDeviceItem(TABLE_DEVICE_RANK, item);
                                        }
                                    }

                                    ArrayList<DeviceInfo> deviceInfos = DBUtil.getAllDeviceInfos(TABLE_DEVICE_RANK);
                                    for (DeviceInfo d : deviceInfos) {
                                        UserInfo.devices.add(d);
                                    }
                                    deviceInfos.clear();
                                }

                                Intent intent = new Intent(MyGroupActivity.this, DeviceSelectActivity.class);
                                intent.putExtra("MODE", "MOVE_GROUP");
                                intent.putExtra(EXTRA_DEVICE_LIST, UserInfo.devices);
                                intent.putExtra(EXTRA_GROUP_ID, UserInfo.dgroups.get(mViewPager.getCurrentItem()).dgroupId);
                                intent.putExtra(EXTRA_GROUP_NAME, UserInfo.dgroups.get(mViewPager.getCurrentItem()).friendlyName);
                                startActivityForResult(intent,RESULT_UPDATE_DATA);

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

    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) {
                            ErrorLogOutput(TAG, "mGroupList size : " + UserInfo.dgroups.size());
                        } else {
                            mViewPager.setAdapter(new MyGroupTabPagerAdapter(MyGroupActivity.this, UserInfo.dgroups, new MyGroupTabPagerAdapter.PressSettingButton() {
                                @Override
                                public void showGroupSettingMenu() {
                                    showSettingMenu();
                                }

                                @Override
                                public void goToAddDevice() {
                                    goToAddDeviceForGroup();
                                }
                            }));
                            mTabGroup.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                                @Override
                                public void onTabSelected(TabLayout.Tab tab) {
                                    LinearLayout tabLayout = (LinearLayout) ((ViewGroup) mTabGroup.getChildAt(0)).getChildAt(tab.getPosition());
                                    TextView tabTextView = (TextView) tabLayout.getChildAt(1);
                                    tabTextView.setTypeface(tabTextView.getTypeface(), Typeface.BOLD);
                                    mViewPager.setCurrentItem(tab.getPosition());
                                }

                                @Override
                                public void onTabUnselected(TabLayout.Tab tab) {
                                    LinearLayout tabLayout = (LinearLayout) ((ViewGroup) mTabGroup.getChildAt(0)).getChildAt(tab.getPosition());
                                    TextView tabTextView = (TextView) tabLayout.getChildAt(1);
                                    tabTextView.setTypeface(tabTextView.getTypeface(), Typeface.NORMAL);
                                }

                                @Override
                                public void onTabReselected(TabLayout.Tab tab) {
                                }
                            });
                            for (DeviceGroupInfo info : UserInfo.dgroups) {
                                mTabGroup.addTab(mTabGroup.newTab().setText(info.friendlyName));
                            }
                            mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabGroup));
                        }
                    }
                });
            }
        });

        /*
        UserInfo.dgroups.clear();
        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"));

                                UserInfo.dgroups.add(item);
                            }

                            //UI 업데이트
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(UserInfo.dgroups.size() == 0) {
                                        ErrorLogOutput(TAG, "mGroupList size : " + UserInfo.dgroups.size());
                                    } else {
                                        mViewPager.getAdapter().notifyDataSetChanged();
                                        for(DeviceGroupInfo info : UserInfo.dgroups) {
                                            mTabGroup.addTab(mTabGroup.newTab().setText(info.friendlyName));
                                        }
                                    }
                                    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();
        }
         */
    }

    private void changeGroup(final String name,final String icon, String background) {
        displayProgress(this,"","");
        try {
            HttpApi.modifyDeviceGroup(UserInfo.dgroups.get(mViewPager.getCurrentItem()).dgroupId,
                    name,
                    icon,
                    background,
                    new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.modifyDeviceGroup(onFailure)\n" + e.toString());
                            showNotiMsg(MyGroupActivity.this,getString(R.string.snackbar_fail_change_group));
                            DismissConnectDialog();
                        }

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

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                showNotiMsg(MyGroupActivity.this,getString(R.string.snackbar_successed_change_group));
                                                if(!name.isEmpty()) {
                                                    UserInfo.dgroups.get(mViewPager.getCurrentItem()).friendlyName = name;
                                                    //TODO - 그룹 이름 갱신 로직 구현해야함.
                                                }
                                                if(!icon.isEmpty()) {
                                                    UserInfo.dgroups.get(mViewPager.getCurrentItem()).icon = icon;
                                                    //TODO - 그룹 이미지 갱신 로직 구현해야함.
                                                }
                                                if(!background.isEmpty()) {
                                                    //TODO - 백그라운드 이미지 저장
                                                }

                                                DismissConnectDialog();
                                                ((MyGroupTabPagerAdapter)mViewPager.getAdapter()).notifyDataSetChanged();
                                            }
                                        });
                                    }
                                });
                            } else if(response.code() == HTTP_UNAUTHORIZED) {
                                showNotiMsg(MyGroupActivity.this, getString(R.string.snackbar_expired_token));
                                restartApp(MyGroupActivity.this);
                            } else {
                                ErrorLogOutput(TAG, "HttpApi.modifyDeviceGroup(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                showNotiMsg(MyGroupActivity.this,getString(R.string.snackbar_fail_change_group));
                                DismissConnectDialog();
                                try {
                                    JSONObject json_data = new JSONObject(response.body().string());
                                    ErrorLogOutput(TAG, "HttpApi.modifyDeviceGroup(onResponse) body : " + json_data.toString());
                                } catch (JSONException e) {
                                    ErrorLogOutput(TAG, "HttpApi.modifyDeviceGroup(onResponse) JSONException : " + e.toString());
                                }
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.modifyDeviceGroup(Exception)\n" + e.toString());
            showNotiMsg(MyGroupActivity.this,getString(R.string.snackbar_fail_change_group));
            DismissConnectDialog();
        }
    }
}