import { closeSocket, connectSocket, onSocketClose, onSocketError, onSocketMessage, onSocketOpen, sendSocketMessage } from "@tarojs/taro";
import { CUSTOME_SOCKET } from "any-hooks/communication/token";
import { AnyRemoteSocketMessage, CustomeSocket } from "any-hooks/types/socket";

export function useCustomeSocket(): CustomeSocket<AnyRemoteSocketMessage> {
  return {
    connect(url: string) {
      connectSocket({url})
    },
    send(data: object) {
      sendSocketMessage({
        data: JSON.stringify(data)
      })
    },
    addEventListener(type: keyof WebSocketEventMap, callback?: (event?: any) => void) {
      switch(type) {
        case 'message':
          onSocketMessage( res => callback({data: JSON.parse(res.data)}) );
          break;
        case 'error':
          onSocketError(callback);
          break;
        case 'open':
          onSocketOpen(callback);
          break;
        case 'close':
          onSocketClose(callback);
          break;
      }
    },
    close() {
      closeSocket()
    },
    removeEventListener() {}
  }
}

useCustomeSocket.token = CUSTOME_SOCKET;