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.DeviceInfo;
import kr.co.icontrols.iotplatform.DataClass.UserInfo;
import kr.co.icontrols.iotplatform.Database.DBUtil;
import kr.co.icontrols.iotplatform.adapter.DeviceSelectAdapter;
import kr.co.icontrols.iotplatform.utils.HttpApi;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static kr.co.icontrols.iotplatform.Database.DatabaseHelper.TABLE_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_LIST;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_GROUP_ID;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_GROUP_NAME;

public class DeviceSelectActivity extends AppCompatActivity implements View.OnClickListener {

    private final String TAG = "GroupSelectActivity";
    private ListView mListView;
    private ArrayList<DeviceInfo> mDeviceList;
    private Handler mHandler;
    private boolean isCompleted;
    private String mMode;
    private String mGroupId;
    private String mGroupName;

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

        isCompleted = false;

        mMode = getIntent().getStringExtra("MODE");
        if(mMode.equals("SMART_LIGHT")) {
            ((TextView)findViewById(R.id.txtTitle)).setText(getString(R.string.delete_favor));
            ((TextView)findViewById(R.id.btnRight)).setText(getString(R.string.delete));
            findViewById(R.id.txtDescription).setVisibility(View.GONE);
        } else if(mMode.equals("AWS")) {
            ((TextView)findViewById(R.id.txtTitle)).setText(getString(R.string.delete_device));
            ((TextView)findViewById(R.id.btnRight)).setText(getString(R.string.delete));
            findViewById(R.id.txtDescription).setVisibility(View.GONE);
        } else if(mMode.equals("MOVE_GROUP")) {
            mGroupId = getIntent().getStringExtra(EXTRA_GROUP_ID);
            mGroupName = getIntent().getStringExtra(EXTRA_GROUP_NAME);

            ((TextView)findViewById(R.id.txtTitle)).setText(getString(R.string.add_device_group));
            ((TextView)findViewById(R.id.btnRight)).setText(getString(R.string.add));
            ((TextView)findViewById(R.id.txtDescription)).setText(String.format(getString(R.string.select_device_description),mGroupName));
            findViewById(R.id.txtDescription).setVisibility(View.VISIBLE);
        }

        mDeviceList = (ArrayList<DeviceInfo>) getIntent().getSerializableExtra(EXTRA_DEVICE_LIST);

        if(mMode.equals("MOVE_GROUP")) {
            for(int i = 0 ; i < mDeviceList.size() ; i++) {
                if(mGroupId.equals(mDeviceList.get(i).dgroupId)) {
                    mDeviceList.remove(i--);
                }
            }
        } else if(mMode.equals("AWS")) {
            for(int i = 0 ; i < mDeviceList.size() ; i++) {
                if(mDeviceList.get(i).ownerId != null && !mDeviceList.get(i).ownerId.isEmpty() && !mDeviceList.get(i).ownerId.equals(UserInfo.uid)) {
                    mDeviceList.remove(i--);
                }
            }
        }


        if(mDeviceList.size() > 0) {
            mListView = findViewById(R.id.listView);
            mListView.setAdapter(new DeviceSelectAdapter(mDeviceList));
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    ((DeviceSelectAdapter) mListView.getAdapter()).setSelected(position);
                    ((DeviceSelectAdapter) mListView.getAdapter()).notifyDataSetChanged();

                    if (((DeviceSelectAdapter) 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);
                    }
                }
            });
        } else {
            if(mMode.equals("MOVE_GROUP")) {
                showNotiMsg(DeviceSelectActivity.this, "추가할 스마트 조명이 존재하지 않습니다.", true);
            } else {
                showNotiMsg(DeviceSelectActivity.this, "삭제할 조명이 존재하지 않습니다.", true);
            }
        }

        mHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                final int index = msg.what;
                if (mDeviceList.size() > index && mDeviceList.get(index).isSelected()) {
                    if (mMode.equals("AWS")) {
                        try {
                            final String deviceId = mDeviceList.get(index).deviceId;
                            HttpApi.deleteDevice(mDeviceList.get(index).deviceId, new okhttp3.Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {
                                    e.printStackTrace();
                                    ErrorLogOutput(TAG, "HttpApi.deleteDevice(onFailure)\n" + e.toString());
                                    showNotiMsg(DeviceSelectActivity.this, "스마트 조명을 삭제하지 못하였습니다.",true);
                                    DismissConnectDialog();
                                }

                                @Override
                                public void onResponse(Call call, Response response) throws IOException {
                                    if (response.code() == HttpApi.HTTP_NO_CONTENT) {
                                        WarnLogOutput(TAG, "HttpApi.deleteDevice(onResponse) HTTP_NO_CONTENT");
                                        DBUtil.removeDeviceInfoAtAllTable(deviceId);
                                        for (int i = 0; i < UserInfo.devices.size(); i++) {
                                            if (UserInfo.devices.get(i).deviceId.equals(deviceId)) {
                                                UserInfo.devices.remove(i);
                                                i--;
                                            }
                                        }
                                        mHandler.sendEmptyMessage(index+1);
                                        isCompleted = true;
                                        //showNotiMsg(DeviceSelectActivity.this,"스마트 조명을 삭제하였습니다.",true);
                                    } else {
                                        ErrorLogOutput(TAG, "HttpApi.deleteDevice(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                        showNotiMsg(DeviceSelectActivity.this, "스마트 조명을 삭제하지 못하였습니다.",true);

                                        try {
                                            JSONObject json_data = new JSONObject(response.body().string());
                                            ErrorLogOutput(TAG, "HttpApi.deleteDevice(onResponse) body : " + json_data.toString());
                                        } catch (JSONException e) {
                                            ErrorLogOutput(TAG, "HttpApi.deleteDevice(onResponse) JSONException : " + e.toString());
                                        }
                                        DismissConnectDialog();
                                    }

                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.deleteDevice(Exception)\n" + e.toString());
                            showNotiMsg(DeviceSelectActivity.this, "스마트 조명을 삭제하지 못하였습니다.",true);
                            DismissConnectDialog();

                        }
                    } else if (mMode.equals("SMART_LIGHT")) {
                        DBUtil.removeDeviceInfo(TABLE_SMART_LIGHT, mDeviceList.get(index));
                        //showNotiMsg(DeviceSelectActivity.this, "스마트 조명을 삭제하였습니다.", true);
                        //DismissConnectDialog();
                        mHandler.sendEmptyMessage(index+1);
                        isCompleted = true;
                    } else if(mMode.equals("MOVE_GROUP")) {
                        try {
                            HttpApi.connectDeviceInDeviceGroup(mGroupId, mDeviceList.get(index).deviceId, new okhttp3.Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {
                                    e.printStackTrace();
                                    ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(onFailure)\n" + e.toString());
                                    showNotiMsg(DeviceSelectActivity.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,mDeviceList.get(index).deviceId);
                                        if(itemS != null) {
                                            itemS.dgroupId = mGroupId;
                                            itemS.dgroupName = mGroupName;
                                            DBUtil.updateDeviceItem(TABLE_SMART_LIGHT,itemS);
                                        }

                                        final DeviceInfo itemH = DBUtil.getDeviceInfoForId(TABLE_DEVICE_HOME,mDeviceList.get(index).deviceId);
                                        if(itemH != null) {
                                            itemH.dgroupId = mGroupId;
                                            itemH.dgroupName = mGroupName;
                                            DBUtil.updateDeviceItem(TABLE_DEVICE_HOME,itemH);
                                        }

                                        final DeviceInfo itemR = DBUtil.getDeviceInfoForId(TABLE_DEVICE_RANK,mDeviceList.get(index).deviceId);
                                        if(itemR != null) {
                                            itemR.dgroupId = mGroupId;
                                            itemR.dgroupName = mGroupName;
                                            DBUtil.updateDeviceItem(TABLE_DEVICE_RANK,itemR);
                                        }

                                        for(int i = 0; i < UserInfo.devices.size() ; i++) {
                                            if(UserInfo.devices.get(i).deviceId.equals(mDeviceList.get(index).deviceId)) {
                                                UserInfo.devices.get(i).dgroupName = mGroupName;
                                                UserInfo.devices.get(i).dgroupId = mGroupId;
                                            }
                                        }

                                        //showNotiMsg(DeviceSelectActivity.this, "그룹을 변경하였습니다.", true);
                                        mHandler.sendEmptyMessage(index+1);
                                        isCompleted = true;
                                    } else {
                                        ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                        showNotiMsg(DeviceSelectActivity.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(DeviceSelectActivity.this, "스마트 조명을 그룹 추가(이동) 중 오류가 발생하였습니다.");
                            DismissConnectDialog();
                        }
                    }
                } else if(mDeviceList.size() > index) {
                    mHandler.sendEmptyMessage(index+1);
                } else {
                    if(isCompleted) {
                        if(mMode.equals("MOVE_GROUP")){
                            showNotiMsg(DeviceSelectActivity.this, "스마트 조명을 그룹에 추가(이동) 하였습니다.", true);
                        } else {
                            showNotiMsg(DeviceSelectActivity.this, "스마트 조명을 삭제하였습니다.", true);
                        }
                    } else {
                        if(mMode.equals("MOVE_GROUP")){
                            showNotiMsg(DeviceSelectActivity.this, "스마트 조명을 그룹 추가(이동) 중 오류가 발생하였습니다.");
                        } else {
                            showNotiMsg(DeviceSelectActivity.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(((DeviceSelectAdapter)mListView.getAdapter()).isSelected()) {
                    displayProgress(this, null, null);
                    mHandler.sendEmptyMessage(0);
                } else {
                    if(mMode.equals("MOVE_GROUP")) {
                        showNotiMsg(DeviceSelectActivity.this,getString(R.string.snackbar_error_select_device_for_group));
                    } else {
                        showNotiMsg(DeviceSelectActivity.this,getString(R.string.snackbar_error_select_device_for_deleting));
                    }
                }
                /*
                final int selectedIndex = ((DeviceSelectAdapter)mListView.getAdapter()).getSelectedIndex();
                if(selectedIndex == -1) {
                    showNotiMsg(DeviceSelectActivity.this,getString(R.string.snackbar_error_select_group_for_deleting));
                } else {
                    if (mMode.equals("AWS")) {
                        displayProgress(this,null,null);
                        try {
                            final String deviceId = mDeviceList.get(selectedIndex).deviceId;
                            HttpApi.deleteDevice(mDeviceList.get(selectedIndex).deviceId, new Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {
                                    e.printStackTrace();
                                    ErrorLogOutput(TAG, "HttpApi.deleteDevice(onFailure)\n" + e.toString());
                                    showNotiMsg(DeviceSelectActivity.this,"스마트 조명을 삭제하지 못하였습니다.");
                                    DismissConnectDialog();
                                }

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

                                        try {
                                            JSONObject json_data = new JSONObject(response.body().string());
                                            ErrorLogOutput(TAG, "HttpApi.deleteDevice(onResponse) body : " + json_data.toString());
                                        } catch (JSONException e) {
                                            ErrorLogOutput(TAG, "HttpApi.deleteDevice(onResponse) JSONException : " + e.toString());
                                        }
                                    }
                                    DismissConnectDialog();
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.deleteDevice(Exception)\n" + e.toString());
                            showNotiMsg(DeviceSelectActivity.this,"스마트 조명을 삭제하지 못하였습니다.");
                            DismissConnectDialog();

                        }
                    } else if(mMode.equals("SMART_LIGHT")) {
                        DBUtil.removeDeviceInfo(TABLE_SMART_LIGHT,mDeviceList.get(selectedIndex));
                        showNotiMsg(DeviceSelectActivity.this,"스마트 조명을 삭제하였습니다.",true);
                        DismissConnectDialog();
                    }
                }
                */
                break;
        }
    }
}