package kr.co.icontrols.iotplatform;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

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

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.adapter.GroupSelectAdapter;
import kr.co.icontrols.iotplatform.utils.HttpApi;
import okhttp3.Call;
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.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.displayProgress;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.showNotiMsg;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_DEVICE_ID;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_DEVICE_NAME;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_GROUP_ID;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_GROUP_LIST;

public class GroupSelectActivity extends AppCompatActivity implements View.OnClickListener {

    private final String TAG = "GroupSelectActivity";
    private ListView mListView;
    private ArrayList<DeviceGroupInfo> mGroupList;
    private Handler mHandler;
    private boolean isCompleted;
    private String mMode;
    private String mDeviceId;
    private String mDeviceName;

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

        isCompleted = false;
        mMode = getIntent().getStringExtra("MODE");

        mListView = findViewById(R.id.listView);

        if(mMode.equals("DELETE")) {
            mGroupList = (ArrayList<DeviceGroupInfo>) getIntent().getSerializableExtra(EXTRA_GROUP_LIST);
            mListView.setAdapter(new GroupSelectAdapter(mGroupList));
            ((TextView)findViewById(R.id.txtTitle)).setText(getString(R.string.delete_group));
            ((TextView)findViewById(R.id.btnRight)).setText(getString(R.string.delete));
            ((TextView)findViewById(R.id.txtDescription)).setText(getString(R.string.delete_group_description));
        } else if(mMode.equals("SELECT")) {
            mGroupList = (ArrayList<DeviceGroupInfo>) getIntent().getSerializableExtra(EXTRA_GROUP_LIST);
            mListView.setAdapter(new GroupSelectAdapter(mGroupList,getIntent().getStringExtra(EXTRA_GROUP_ID)));
            mDeviceId = getIntent().getStringExtra(EXTRA_DEVICE_ID);
            mDeviceName = getIntent().getStringExtra(EXTRA_DEVICE_NAME);
            ((TextView)findViewById(R.id.txtTitle)).setText(getString(R.string.change_group));
            ((TextView)findViewById(R.id.btnRight)).setText(getString(R.string.save));
            ((TextView)findViewById(R.id.txtDescription)).setText(String.format(getString(R.string.select_group_description),mDeviceName));
        }
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if(mMode.equals("SELECT")) {
                    ((GroupSelectAdapter)mListView.getAdapter()).setSelectedForSingle(position);
                } else {
                    if(position == 0) {
                        showNotiMsg(GroupSelectActivity.this, "기본그룹은 삭제가 불가능합니다.");
                    } else {
                        ((GroupSelectAdapter) mListView.getAdapter()).setSelected(position);
                    }
                }

                ((GroupSelectAdapter)mListView.getAdapter()).notifyDataSetChanged();

                if(((GroupSelectAdapter)mListView.getAdapter()).isSelected()) {
                    findViewById(R.id.btnBack).setVisibility(View.GONE);
                    findViewById(R.id.btnBackText).setVisibility(View.VISIBLE);
                    findViewById(R.id.btnRight).setVisibility(View.VISIBLE);
                } else {
                    findViewById(R.id.btnBack).setVisibility(View.VISIBLE);
                    findViewById(R.id.btnBackText).setVisibility(View.GONE);
                    findViewById(R.id.btnRight).setVisibility(View.INVISIBLE);
                }
            }
        });

        mHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                final int index = msg.what;
                if (mGroupList.size() > index && mGroupList.get(index).isSelected()) {
                    if(mMode.equals("DELETE")) {
                        try {
                            HttpApi.deleteDeviceGroup(mGroupList.get(index).dgroupId, new okhttp3.Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {
                                    e.printStackTrace();
                                    ErrorLogOutput(TAG, "HttpApi.deleteDeviceGroup(onFailure)\n" + e.toString());
                                    showNotiMsg(GroupSelectActivity.this, "그룹을 삭제중 오류가 발생하였습니다.");
                                    DismissConnectDialog();
                                }

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

                                        if(mGroupList.size() > 0) {
                                            final ArrayList<DeviceInfo> itemS = DBUtil.getDeviceInfoForGroupId(TABLE_SMART_LIGHT, mGroupList.get(index).dgroupId);
                                            if (itemS != null) {
                                                for(DeviceInfo d : itemS) {
                                                    d.dgroupId = mGroupList.get(0).dgroupId;
                                                    d.dgroupName = mGroupList.get(0).friendlyName;
                                                    DBUtil.updateDeviceItem(TABLE_SMART_LIGHT, d);
                                                }
                                                itemS.clear();
                                            }

                                            final ArrayList<DeviceInfo> itemH = DBUtil.getDeviceInfoForGroupId(TABLE_DEVICE_HOME, mGroupList.get(index).dgroupId);
                                            if (itemH != null) {
                                                for(DeviceInfo d : itemH) {
                                                    d.dgroupId = mGroupList.get(0).dgroupId;
                                                    d.dgroupName = mGroupList.get(0).friendlyName;
                                                    DBUtil.updateDeviceItem(TABLE_DEVICE_HOME, d);
                                                }
                                                itemH.clear();
                                            }

                                            final ArrayList<DeviceInfo> itemR = DBUtil.getDeviceInfoForGroupId(TABLE_DEVICE_RANK, mGroupList.get(index).dgroupId);
                                            if (itemR != null) {
                                                for(DeviceInfo d : itemR) {
                                                    d.dgroupId = mGroupList.get(0).dgroupId;
                                                    d.dgroupName = mGroupList.get(0).friendlyName;
                                                    DBUtil.updateDeviceItem(TABLE_DEVICE_RANK, d);
                                                }
                                                itemR.clear();
                                            }

                                            for (int i = 0; i < UserInfo.devices.size(); i++) {
                                                if (UserInfo.devices.get(i).dgroupId.equals(mGroupList.get(index).dgroupId)) {
                                                    UserInfo.devices.get(i).dgroupName = mGroupList.get(0).friendlyName;
                                                    UserInfo.devices.get(i).dgroupId = mGroupList.get(0).dgroupId;
                                                }
                                            }
                                        }

                                        mHandler.sendEmptyMessage(index+1);
                                        isCompleted = true;
                                        //showNotiMsg(GroupSelectActivity.this, "그룹을 삭제하였습니다.", MyGroupActivity.class);
                                    } else {
                                        ErrorLogOutput(TAG, "HttpApi.deleteDeviceGroup(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                        showNotiMsg(GroupSelectActivity.this, "그룹을 삭제중 오류가 발생하였습니다.");
                                        try {
                                            JSONObject json_data = new JSONObject(response.body().string());
                                            ErrorLogOutput(TAG, "HttpApi.deleteDeviceGroup(onResponse) body : " + json_data.toString());
                                        } catch (JSONException e) {
                                            ErrorLogOutput(TAG, "HttpApi.deleteDeviceGroup(onResponse) JSONException : " + e.toString());
                                        }
                                        DismissConnectDialog();
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.deleteDeviceGroup(Exception)\n" + e.toString());
                            showNotiMsg(GroupSelectActivity.this, "그룹을 삭제중 오류가 발생하였습니다.");
                            DismissConnectDialog();
                        }
                    } else if(mMode.equals("SELECT")) {
                        try {
                            HttpApi.connectDeviceInDeviceGroup(mGroupList.get(index).dgroupId, mDeviceId, new okhttp3.Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {
                                    e.printStackTrace();
                                    ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(onFailure)\n" + e.toString());
                                    showNotiMsg(GroupSelectActivity.this, "그룹 이동 중 오류가 발생하였습니다.");
                                    DismissConnectDialog();
                                }

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

                                        final DeviceInfo itemS = DBUtil.getDeviceInfoForId(TABLE_SMART_LIGHT,mDeviceId);
                                        if(itemS != null) {
                                            itemS.dgroupId = mGroupList.get(index).dgroupId;
                                            itemS.dgroupName = mGroupList.get(index).friendlyName;
                                            DBUtil.updateDeviceItem(TABLE_SMART_LIGHT,itemS);
                                        }

                                        final DeviceInfo itemH = DBUtil.getDeviceInfoForId(TABLE_DEVICE_HOME,mDeviceId);
                                        if(itemH != null) {
                                            itemH.dgroupId = mGroupList.get(index).dgroupId;
                                            itemH.dgroupName = mGroupList.get(index).friendlyName;
                                            DBUtil.updateDeviceItem(TABLE_DEVICE_HOME,itemH);
                                        }

                                        final DeviceInfo itemR = DBUtil.getDeviceInfoForId(TABLE_DEVICE_RANK,mDeviceId);
                                        if(itemR != null) {
                                            itemR.dgroupId = mGroupList.get(index).dgroupId;
                                            itemR.dgroupName = mGroupList.get(index).friendlyName;
                                            DBUtil.updateDeviceItem(TABLE_DEVICE_RANK,itemR);
                                        }

                                        for(int i = 0; i < UserInfo.devices.size() ; i++) {
                                            if(UserInfo.devices.get(i).deviceId.equals(mDeviceId)) {
                                                UserInfo.devices.get(i).dgroupName = mGroupList.get(index).friendlyName;
                                                UserInfo.devices.get(i).dgroupId = mGroupList.get(index).dgroupId;
                                            }
                                        }
                                        mHandler.sendEmptyMessage(index+1);
                                        isCompleted = true;
                                        //showNotiMsg(GroupSelectActivity.this, "그룹을 변경하였습니다.", true);
                                    } else {
                                        ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                        showNotiMsg(GroupSelectActivity.this, "그룹 이동 중 오류가 발생하였습니다.");
                                        try {
                                            JSONObject json_data = new JSONObject(response.body().string());
                                            ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(onResponse) body : " + json_data.toString());
                                        } catch (JSONException e) {
                                            ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(onResponse) JSONException : " + e.toString());
                                        }
                                        DismissConnectDialog();
                                    }
                                }
                            });
                        }  catch (Exception e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(Exception)\n" + e.toString());
                            showNotiMsg(GroupSelectActivity.this, "그룹 이동 중 오류가 발생하였습니다.");
                            DismissConnectDialog();
                        }
                    }
                } else if(mGroupList.size() > index) {
                    mHandler.sendEmptyMessage(index+1);
                } else {
                    if(isCompleted) {
                        if(mMode.equals("SELECT")){
                            showNotiMsg(GroupSelectActivity.this, "그룹을 변경하였습니다.", true);
                        } else {
                            UserInfo.dgroups.clear();
                            showNotiMsg(GroupSelectActivity.this, "그룹을 삭제하였습니다.", MyGroupActivity.class);
                        }
                    } else {
                        if(mMode.equals("SELECT")){
                            showNotiMsg(GroupSelectActivity.this, "그룹 이동 중 오류가 발생하였습니다.");
                        } else {
                            showNotiMsg(GroupSelectActivity.this, "그룹을 삭제중 오류가 발생하였습니다.");
                        }
                    }
                    DismissConnectDialog();
                }
            }
        };
    }

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

    @Override
    protected void onPause() {
        ForceDismissConnectDialog();
        super.onPause();
    }

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

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

        switch (v.getId()) {
            case R.id.btnBack:
            case R.id.btnBackText:
                onBackPressed();
                break;
            case R.id.btnRight:
                if(((GroupSelectAdapter)mListView.getAdapter()).isSelected()) {
                    displayProgress(this, null, null);
                    mHandler.sendEmptyMessage(0);
                } else {
                    if(mMode.equals("DELETE")) {
                        showNotiMsg(GroupSelectActivity.this, "삭제할 그룹을 선택해주세요.");
                    } else {
                        showNotiMsg(GroupSelectActivity.this,"변경할 그룹을 선택해주세요.");
                    }
                }
                /*
                final int selectedIndex = ((GroupSelectAdapter)mListView.getAdapter()).getSelectedIndex();

                if(mMode.equals("DELETE")) {
                    if (selectedIndex == -1) {
                        showNotiMsg(GroupSelectActivity.this, "삭제할 그룹을 선택해주세요.");
                    } else {
                        displayProgress(this, "", "");
                        try {
                            HttpApi.deleteDeviceGroup(mGroupList.get(selectedIndex).dgroupId, new Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {
                                    e.printStackTrace();
                                    ErrorLogOutput(TAG, "HttpApi.deleteDeviceGroup(onFailure)\n" + e.toString());
                                    showNotiMsg(GroupSelectActivity.this, "그룹을 삭제중 오류가 발생하였습니다.");
                                    DismissConnectDialog();
                                }

                                @Override
                                public void onResponse(Call call, Response response) throws IOException {
                                    if (response.code() == HttpApi.HTTP_NO_CONTENT) {
                                        WarnLogOutput(TAG, "HttpApi.deleteDeviceGroup(onResponse) HTTP_NO_CONTENT");
                                        showNotiMsg(GroupSelectActivity.this, "그룹을 삭제하였습니다.", MyGroupActivity.class);
                                    } else {
                                        ErrorLogOutput(TAG, "HttpApi.deleteDeviceGroup(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                        showNotiMsg(GroupSelectActivity.this, "그룹을 삭제중 오류가 발생하였습니다.");
                                        try {
                                            JSONObject json_data = new JSONObject(response.body().string());
                                            ErrorLogOutput(TAG, "HttpApi.deleteDeviceGroup(onResponse) body : " + json_data.toString());
                                        } catch (JSONException e) {
                                            ErrorLogOutput(TAG, "HttpApi.deleteDeviceGroup(onResponse) JSONException : " + e.toString());
                                        }
                                    }
                                    DismissConnectDialog();
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.deleteDeviceGroup(Exception)\n" + e.toString());
                            showNotiMsg(GroupSelectActivity.this, "그룹을 삭제중 오류가 발생하였습니다.");
                            DismissConnectDialog();
                        }
                    }
                } else if(mMode.equals("SELECT")) {
                    if (selectedIndex == -1) {
                        showNotiMsg(GroupSelectActivity.this, "변경할 그룹을 선택해주세요.");
                    } else {
                        displayProgress(this, "", "");
                        try {
                            HttpApi.connectDeviceInDeviceGroup(mGroupList.get(selectedIndex).dgroupId, mDeviceId, new Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {
                                    e.printStackTrace();
                                    ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(onFailure)\n" + e.toString());
                                    showNotiMsg(GroupSelectActivity.this, "그룹 이동 중 오류가 발생하였습니다.");
                                    DismissConnectDialog();
                                }

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

                                        final DeviceInfo itemS = DBUtil.getDeviceInfoForId(TABLE_SMART_LIGHT,mDeviceId);
                                        if(itemS != null) {
                                            itemS.dgroupId = mGroupList.get(selectedIndex).dgroupId;
                                            itemS.dgroupName = mGroupList.get(selectedIndex).friendlyName;
                                            DBUtil.updateDeviceItem(TABLE_SMART_LIGHT,itemS);
                                        }

                                        final DeviceInfo itemH = DBUtil.getDeviceInfoForId(TABLE_DEVICE_HOME,mDeviceId);
                                        if(itemH != null) {
                                            itemH.dgroupId = mGroupList.get(selectedIndex).dgroupId;
                                            itemH.dgroupName = mGroupList.get(selectedIndex).friendlyName;
                                            DBUtil.updateDeviceItem(TABLE_DEVICE_HOME,itemH);
                                        }

                                        final DeviceInfo itemR = DBUtil.getDeviceInfoForId(TABLE_DEVICE_RANK,mDeviceId);
                                        if(itemR != null) {
                                            itemR.dgroupId = mGroupList.get(selectedIndex).dgroupId;
                                            itemR.dgroupName = mGroupList.get(selectedIndex).friendlyName;
                                            DBUtil.updateDeviceItem(TABLE_DEVICE_RANK,itemR);
                                        }

                                        for(int i = 0; i < UserInfo.devices.size() ; i++) {
                                            if(UserInfo.devices.get(i).deviceId.equals(mDeviceId)) {
                                                UserInfo.devices.get(i).dgroupName = mGroupList.get(selectedIndex).friendlyName;
                                                UserInfo.devices.get(i).dgroupId = mGroupList.get(selectedIndex).dgroupId;
                                            }
                                        }

                                        showNotiMsg(GroupSelectActivity.this, "그룹을 변경하였습니다.", true);
                                    } else {
                                        ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                        showNotiMsg(GroupSelectActivity.this, "그룹 이동 중 오류가 발생하였습니다.");
                                        try {
                                            JSONObject json_data = new JSONObject(response.body().string());
                                            ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(onResponse) body : " + json_data.toString());
                                        } catch (JSONException e) {
                                            ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(onResponse) JSONException : " + e.toString());
                                        }
                                    }
                                    DismissConnectDialog();
                                }
                            });
                        }  catch (Exception e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(Exception)\n" + e.toString());
                            showNotiMsg(GroupSelectActivity.this, "그룹 이동 중 오류가 발생하였습니다.");
                            DismissConnectDialog();
                        }
                    }
                }
                 */
                break;
        }
    }
}