import useBluetooth from '@/hooks/useBluetooth';
import useDeviceWS from '@/hooks/useDeviceWS';
import { WM_SOCKET_URL } from '@/constants';
import { useEffect, useState } from '@tarojs/taro';
import { str2ab } from '@/utils/arrayBuffer';

const useWasherStart = (code: string) => {
  const errorData: Error | null = useState(null);

  const services = [
    '6E401103-B5A3-F393-E0A9-E50E24DCCA9E',
    '6E400002-B5A3-F393-E0A9-E50E24DCCA9E',
    '6E400003-B5A3-F393-E0A9-E50E24DCCA9E',
  ];
  const getBluetoothData = (data: string) => {
    sendMessageToServer(
      data,
      res => {
        console.log(res);
      },
      err => {
        console.log(err);
      }
    );
  };
  const getSocketData = (data: string) => {
    sendMessageToDevice(data);
  };
  const {
    state: wsState,
    sendMessageToServer,
    connectDeviceSocket,
  } = useDeviceWS({
    url: WM_SOCKET_URL,
    getSocketData,
  });
  const {
    state: bluetoothState,
    sendMessageToDevice,
    devicesDiscoveryHandle,
  } = useBluetooth({
    getBluetoothData,
    services,
  });

  useEffect(() => {
    console.log('useWasherStart useEffect code', code);
    if (code) {
      connectDeviceSocket();
      devicesDiscoveryHandle(code);
    }
  }, [code]);

  useEffect(() => {
    if (code) {
      if (bluetoothState && wsState.socketState && wsState.socketTask) {
        let deviceData = '{<' + code + '>}';
        console.log('<---发送设备编号:', deviceData);
        wsState.socketTask.send({
          data: str2ab(deviceData),
          success: msg => {
            console.log('发送设备编号:', msg, '--->');
          },
          fail: err => {
            console.log('发送设备编号:', err, '--->');
          },
        });
      }
    }
  }, [bluetoothState, wsState.socketState, code]);

  return {
    errorData,
    wsState,
    bluetoothState,
  };
};

export default useWasherStart;
