package com.motse.fengshui_compass.ui.home;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.licheedev.hwutils.ByteUtil;
import com.motse.fengshui_compass.common.Device;
import com.motse.fengshui_compass.common.RotateThread;
import com.motse.fengshui_compass.common.SerialPortManager;

public class HomeViewModel extends ViewModel {

    private final MutableLiveData<Float> rotation;
    private MutableLiveData<Boolean> isSerialOpen;
    RotateThread rotateThread;
    private final Handler handler;
    private final Handler serialThreadHandle;
    private final SerialPortManager serialPortManager;

    public HomeViewModel() {
        isSerialOpen = new MutableLiveData<>();
        isSerialOpen.setValue(false);
        serialPortManager = SerialPortManager.instance();
        handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                Float _rotation = msg.getData().getFloat("rotation");
                rotation.setValue(_rotation);
            }
        };
        serialThreadHandle = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                String data = msg.getData().getString("hex_str");
                System.out.println(data);
            }
        };
        rotation = new MutableLiveData<>();
        rotation.setValue((float) 0);
    }

    public void initThread() {
        rotateThread = new RotateThread(handler);
        rotateThread.start();
    }

    public void initSerialPort() {
        Device device = new Device();
        device.setBaudrate("115200");
        device.setPath("/dev/ttyS2");
        serialPortManager.open(device, serialThreadHandle);
    }

    public void destroySerialPort() {
        serialPortManager.close();
    }

    public void openUpLaser() {
        sendCommand("7E01010100000000000000010D0A");
    }

    public void sendCommand(String command) {
        byte[] bytes = ByteUtil.hexStr2bytes(command);
        try {
            serialPortManager.sendData(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public void destroyThread() {
        rotateThread.interrupt();
        rotateThread = null;
    }

    public LiveData<Float> getRotation() {
        return rotation;
    }
}