import { SHIP_SOS_WS_URL } from '@/constants/slave/sgw/websocket';
import { wsClient } from '@/utils/wsClient';
import { useCallback, useState } from 'react';

export default function useGetShipSos() {
  const [shipSos, setShipSos] = useState<WsTypes.WsThingResponse | null>(null);
  const [loading, setLoading] = useState(false);

  const getShipSosWs = useCallback(async () => {
    setLoading(true);
    try {
      wsClient.connect(SHIP_SOS_WS_URL, true);
      const unsubscribe = wsClient.subscribe(
        (data: WsTypes.WsThingResponse) => {
          setShipSos((pre) => {
            if (pre?.time && data.time && pre.time > data.time) {
              return pre;
            }
            return data;
          });
          setLoading(false);
        },
      );
      return unsubscribe;
    } catch (error) {
      console.error('Error when get Ship SOS: ', error);
    }
  }, []);
  return { shipSos, getShipSosWs, loading };
}
