package kr.co.icontrols.iotplatform;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

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.Database.DatabaseHelper;
import kr.co.icontrols.iotplatform.adapter.DeviceSelectAdapter;

import static kr.co.icontrols.iotplatform.Database.DatabaseHelper.TABLE_SMART_LIGHT;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.ForceDismissConnectDialog;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.showNotiMsg;
public class AddHomeActivity extends AppCompatActivity implements View.OnClickListener {

    private final String TAG = "AddHomeActivity";
    private ListView mListView;
    private ArrayList<DeviceInfo> mDeviceList = new ArrayList<>();

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

        mListView = findViewById(R.id.listView);
        UserInfo.setUnSelectAllDevices();
        getDeviceList();
    }

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

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

    @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()) {
                    showNotiMsg(AddHomeActivity.this,"추가할 스마트 조명을 선택해주세요.");
                } else{
                    boolean isCompleted = false;
                    for(int i = 0; i < mDeviceList.size() ; i++) {
                        if(mDeviceList.get(i).isSelected()) {
                            if (DBUtil.getDeviceInfoForId(TABLE_SMART_LIGHT, mDeviceList.get(i).deviceId) != null) {
                                //showNotiMsg(AddHomeActivity.this, "스마트 조명에 이미 추가된 조명입니다.");
                            } else {
                                if (DBUtil.putDeviceInfo(TABLE_SMART_LIGHT, mDeviceList.get(i)) == -1) {
                                    //showNotiMsg(AddHomeActivity.this, "스마트 조명 등록에 실패하였습니다.");
                                } else {
                                    //showNotiMsg(AddHomeActivity.this, "스마트 조명 등록을 완료하였습니다.", true);
                                    isCompleted = true;
                                }
                            }
                        }
                    }
                    if(isCompleted) {
                        showNotiMsg(AddHomeActivity.this, "스마트 조명 등록을 완료하였습니다.", true);
                    } else {
                        showNotiMsg(AddHomeActivity.this, "스마트 조명 등록에 실패하였습니다.");
                    }
                }
                break;
        }
    }

    private void getDeviceList() {

        UserInfo.getDevice(this, new UserInfo.CallbackForUpdate() {
            @Override
            public void updateData() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mDeviceList.clear();
                        if(UserInfo.devices.size() > 0) {
                            for (DeviceInfo d : UserInfo.devices) {
                                mDeviceList.add(d);
                            }
                            ArrayList<DeviceInfo> tempDevices = DBUtil.getAllDeviceInfos(TABLE_SMART_LIGHT);
                            for (int i = 0; i < mDeviceList.size(); i++) {
                                for (DeviceInfo d : tempDevices) {
                                    if (d.deviceId.equals(mDeviceList.get(i).deviceId)) {
                                        mDeviceList.remove(i--);
                                        break;
                                    }
                                }
                            }
                            tempDevices.clear();
                        }

                        if(mDeviceList.size() > 0) {
                            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 {
                            showNotiMsg(AddHomeActivity.this, "추가 가능한 스마트 조명이 존재하지 않습니다.",true);
                        }
                    }
                });
            }
        });
        /*
        try{
            displayProgress(AddHomeActivity.this,"","");
            HttpApi.getAllDevice(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    ErrorLogOutput(TAG, "HttpApi.getAllDevice(onFailure)\n" + e.toString());
                    showNotiMsg(AddHomeActivity.this,"스마트 조명 목록 획득을 실패하였습니다.");
                    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());
                            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
                                );
                                mDeviceList.add(item);
                            }

                            //UI 업데이트
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ((DeviceSelectAdapter)mListView.getAdapter()).notifyDataSetChanged();
                                    DismissConnectDialog();
                                }
                            });

                        } catch (JSONException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.getAllDevice(JSONException)\n" + e.toString());
                            showNotiMsg(AddHomeActivity.this,"스마트 조명 목록 획득을 실패하였습니다.");
                            DismissConnectDialog();
                        }
                    } else {
                        ErrorLogOutput(TAG, "HttpApi.getAllDevice(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                        showNotiMsg(AddHomeActivity.this,"스마트 조명 목록 획득을 실패하였습니다.");
                        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());
            showNotiMsg(AddHomeActivity.this,"스마트 조명 목록 획득을 실패하였습니다.");
            DismissConnectDialog();
        }
         */
    }
}