package aicare.net.cn.sdk.ailinksdkdemoandroid.modules.barometric_temp_humidity;

import android.app.AlertDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.pingwang.bluetoothlib.AILinkBleManager;
import com.pingwang.bluetoothlib.device.BleDevice;
import com.pingwang.bluetoothlib.listener.OnCallbackBle;
import com.pingwang.bluetoothlib.utils.BleLog;
import com.pingwang.bluetoothlib.utils.BleStrUtils;

import java.util.ArrayList;
import java.util.List;

import aicare.net.cn.sdk.ailinksdkdemoandroid.R;
import aicare.net.cn.sdk.ailinksdkdemoandroid.base.BleNewBaseActivity;
import aicare.net.cn.sdk.ailinksdkdemoandroid.config.BleDeviceConfig;
import cn.net.aicare.modulelibrary.module.BoraTempHumidity.BarometricTempHumidityBleData;
import cn.net.aicare.modulelibrary.module.BoraTempHumidity.BleSendUtils;

/**
 * @author yesp
 */
public class BarometricTempHygrometerActivity extends BleNewBaseActivity implements BarometricTempHumidityBleData.BaroTempHygrometerListener,
        OnCallbackBle, BarometricTempHumidityBleData.LogInterface {

    private static final String TAG = "BarometricTempHygrometerActivity";
    private BarometricTempHumidityBleData mBarometricTempHumidityBleData;
    private String mAddress;
    private ListView lvLogs;
    private List<String> mLogList;
    private ArrayAdapter<String> listAdapter;
    private RecyclerView rvInstruction;
    private InstructionAdapter mInstructionAdapter;
    private List<String> mHistoryList;
    private EditText etTime;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_barometric_temp_humidity);
        initView();
    }

    private void initView() {
        lvLogs = findViewById(R.id.lv_log);
        mLogList = new ArrayList<>();
        listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mLogList);
        lvLogs.setAdapter(listAdapter);
        mHistoryList = new ArrayList<>();
        rvInstruction = findViewById(R.id.rv_inst);
        rvInstruction.setLayoutManager(new LinearLayoutManager(this));
        mInstructionAdapter = new InstructionAdapter(this, getInstructionList());
        rvInstruction.setAdapter(mInstructionAdapter);
        mInstructionAdapter.setItemClickListener(this::sendInstruction);
        etTime = findViewById(R.id.et_time);
    }

    public static ArrayList<InstructionBean> getInstructionList() {
        ArrayList<InstructionBean> list = new ArrayList<>();

        list.add(new InstructionBean(0, "获取支持功能"));
        list.add(new InstructionBean(1, "获取设备状态"));
        list.add(new InstructionBean(2, "设置设备变化阀值: 1℃, 1% , 10hpa"));
        list.add(new InstructionBean(3, "设置设备变化阀值: 2℃, 2% , 20hpa"));
        list.add(new InstructionBean(4, "读取设备的历史数据: time - 0"));
        list.add(new InstructionBean(5, "读取设备的历史数据: 自定义time"));
        list.add(new InstructionBean(6, "发下一组离线数据"));
        list.add(new InstructionBean(7, "离线数据接收完毕"));
        list.add(new InstructionBean(8, "设置采样频率(10s),保存频率(20s), 间隔(2s)"));
        list.add(new InstructionBean(9, "设置采样频率(自定义)"));
        list.add(new InstructionBean(10, "读取校准值"));
        list.add(new InstructionBean(11, "设置校准值: +1℃, +1% , +10hpa"));
        list.add(new InstructionBean(12, "设置校准值: -1℃, -1% , -10hpa"));
        list.add(new InstructionBean(13, "开始寻物"));
        list.add(new InstructionBean(14, "停止寻物"));
        list.add(new InstructionBean(15, "读取蜂鸣器状态"));
        list.add(new InstructionBean(16, "设置蜂鸣器-开"));
        list.add(new InstructionBean(17, "设置蜂鸣器-关"));
        list.add(new InstructionBean(18, "绑定设备"));
        return list;
    }

    private void sendInstruction(InstructionBean bean) {
        if (bean == null || mBarometricTempHumidityBleData == null) {
            return;
        }
        byte[] sendBytes = null;
        switch (bean.getIndex()) {
            case 0:
                sendBytes = BleSendUtils.getSupportFunction();
                break;
            case 1:
                sendBytes = BleSendUtils.getDeviceStatus();
                break;
            case 2:
                sendBytes = BleSendUtils.setThreshold(10, 10, 10);
                break;
            case 3:
                sendBytes = BleSendUtils.setThreshold(20, 20, 20);
                break;
            case 4:
                sendBytes = BleSendUtils.getOfflineRecord(0);
                break;
            case 5:
                String time = etTime.getText().toString().trim();
                if (TextUtils.isEmpty(time)) {
                    addLog("请在顶部输入时间");
                    return;
                } else {
                    sendBytes = BleSendUtils.getOfflineRecord(Long.parseLong(time));
                }
                break;
            case 6:
                sendBytes = BleSendUtils.sendOfflineStatus(1);
                break;
            case 7:
                sendBytes = BleSendUtils.sendOfflineStatus(0);
                break;
            case 8:
                sendBytes = BleSendUtils.setFrequency(5, 10, 20);
                break;
            case 9:
                EditParamsDialog dialog = EditParamsDialog.newInstance();
                dialog.setOnDialogListener(new EditParamsDialog.OnDialogListener() {
                    @Override
                    public void tvCancelListener(View v) {
                    }

                    @Override
                    public void tvSucceedListener(View v, int value1, int value2, int value3) {
                        byte[] sendBytesT = BleSendUtils.setFrequency(value1, value2, value3);
                        mBarometricTempHumidityBleData.sendDataA7(sendBytesT);
                        addLog(bean.getName() + ", 发送的 payload 数据:\n" + BleStrUtils.byte2HexStr(sendBytesT));
                    }
                });
                dialog.show(getSupportFragmentManager());
                break;
            case 10:
                sendBytes = BleSendUtils.getCalibration();
                break;
            case 11:
                sendBytes = BleSendUtils.setCalibration(10, 10, 10);
                break;
            case 12:
                sendBytes = BleSendUtils.setCalibration(-10, -10, -10);
                break;
            case 13:
                sendBytes = BleSendUtils.findDevice(0);
                break;
            case 14:
                sendBytes = BleSendUtils.findDevice(1);
                break;
            case 15:
                sendBytes = BleSendUtils.getSound();
                break;
            case 16:
                sendBytes = BleSendUtils.setSound(true);
                break;
            case 17:
                sendBytes = BleSendUtils.setSound(false);
                break;
            case 18:
                sendBytes = BleSendUtils.startBindDevice();
                break;
            default:
                break;
        }
        if (sendBytes != null) {
            mBarometricTempHumidityBleData.sendDataA7(sendBytes);
            addLog(bean.getName() + ", 发送的 payload 数据:\n" + BleStrUtils.byte2HexStr(sendBytes));
        }
    }


    @Override
    public void onServiceSuccess() {
        if (AILinkBleManager.getInstance() != null) {
            mAddress = getIntent().getStringExtra("mac");
            AILinkBleManager.getInstance().setOnCallbackBle(this);
            BleDevice bleDevice = AILinkBleManager.getInstance().getBleDevice(mAddress);
            BarometricTempHumidityBleData.init(bleDevice, BleDeviceConfig.BAROMETRIC_TEMP_HUMIDITY);
            mBarometricTempHumidityBleData = BarometricTempHumidityBleData.getInstance();
            mBarometricTempHumidityBleData.setBaroTempHygrometerListener(this);
            mBarometricTempHumidityBleData.setLogInterface(this);
        }
    }

    @Override
    public void onDisConnected(String mac, int code) {
        if (mac.equals(mAddress) && getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)) {
            BleLog.i(TAG, "设备断开连接，请退出重新连接");
            new AlertDialog.Builder(this)
                    .setTitle("ERROR：")
                    .setMessage("\n" + "设备断开连接，请退出重新连接")
                    .setPositiveButton("确认", (dialog, which) -> finish())
                    .show();
        }
    }

    private void addLog(String str) {
        mLogList.add(str);
        listAdapter.notifyDataSetChanged();
        lvLogs.smoothScrollToPosition(listAdapter.getCount() - 1);
    }

    private void addLog(List<String> strList) {
        mLogList.addAll(strList);
        listAdapter.notifyDataSetChanged();
        lvLogs.smoothScrollToPosition(listAdapter.getCount() - 1);
    }


    @Override
    public void onServiceErr() {

    }

    @Override
    public void unbindServices() {
        AILinkBleManager.getInstance().disconnect(mAddress);
        if (mBarometricTempHumidityBleData != null) {
            mBarometricTempHumidityBleData.clear();
            mBarometricTempHumidityBleData = null;
        }
    }

    @Override
    public void onDeviceStatus(int battery, long time, int temp, int humidity, int barometric) {
        addLog("当前设备状态：电量：" + battery + ", 开机时间：" + time + ", 温度：" + temp / 10f + "℃, 湿度：" + humidity / 10 + "%, 气压：" + barometric);
    }

    @Override
    public void onFunctionList(int calibration, int buzzerAlarm, int alarmFunction, int reportPunctually, int nightLight, int bgLight, int findDevice, byte[] bytes) {
        addLog("当前支持功能：气压温湿度校准：" + (calibration == 1) +
                ", \n蜂鸣器报警：" + (buzzerAlarm == 1) +
                ", \n闹钟功能：" + (alarmFunction == 1) +
                ", \n整点报时：" + (reportPunctually == 1) +
                ", \n小夜灯：" + (nightLight == 1) +
                ", \n背光亮度：" + (bgLight == 1) +
                ", \n寻物功能：" + (findDevice == 1));
    }

    @Override
    public void onOffLineRecordNum(long total, long sendNum) {
        addLog("离线记录总数: " + "总数：" + total + ", 已发数量：" + sendNum);
        addLog(mHistoryList);
        mHistoryList.clear();
    }

    @Override
    public void onOffLineRecord(long time, int temp, int humidity, int barometric) {
        mHistoryList.add("离线记录：" + "时间：" + time + ", 温度：" + temp / 10f + "℃, 湿度：" + humidity / 10f + "%, 气压：" + barometric + "hpa");
    }

    @Override
    public void onVersion(String version) {

    }

    @Override
    public void onThreshold(int tempT, int humidityT, int barometricT) {
        addLog("当前设备变化阀值：" + "温度：" + tempT / 10f + "℃, 湿度：" + humidityT / 10f + "%, 气压：" + barometricT + "hpa");
    }

    @Override
    public void onFrequency(int samplingFrequency, int saveFrequency, int timerInterval) {
        int interval = timerInterval * 100;
        addLog("当前频率：" + "采样频率：" + samplingFrequency * interval + "ms, 保存频率：" + saveFrequency * interval + "ms, 设备定时器间隔：" + interval + "ms");
    }

    @Override
    public void onFindDevice(int status) {
        String result;
        if (status == 0) {
            result = "正在报警";
        } else if (status == 1) {
            result = "停止报警";
        } else {
            result = "未知";
        }
        addLog("寻物状态：" + result);
    }

    @Override
    public void onBuzzer(boolean isOpen) {
        addLog("蜂鸣器状态：" + (isOpen ? "开" : "关"));
    }

    @Override
    public void onCalibration(int tempCal, int humidityCal, int barometricCal) {
        addLog("当前校准值：" + "温度：" + tempCal / 10f + "℃, 湿度：" + humidityCal / 10f + "%, 气压：" + barometricCal + "hpa");
    }

    @Override
    public void onBindStatus(boolean success) {
        addLog("绑定设备结果：" + (success ? "成功" : "失败"));
    }

    @Override
    public void onLog(byte[] bytes) {
        addLog("接收到的 payload 数据：" + BleStrUtils.byte2HexStr(bytes));
    }
}
