import { encode as encodeMP, decode as decodeMP } from "@msgpack/msgpack";

export const CLIENT_PROTOCOL = "odynet-a1";

interface ServerCmdHello {
  type: "Hello";
  server_name: string;
  protocol_ver: string;
}

interface ServerCmdError {
  type: "Error";
  error_msg: string;
}

type ServerMessage = ServerCmdHello | ServerCmdError;

interface ClientCmdHello {
  type: "Hello";
}

type ClientMessage = ClientCmdHello;

export enum ServerMessageCode {
  Hello = 0,
  Error = 1,
}

export enum ClientMessageCode {
  Hello = 0,
}

export function decode(data: ArrayBuffer): ServerMessage {
  const obj = decodeMP(data);
  const msgtype = parseInt(Object.keys(obj)[0], 10) as ServerMessageCode;
  const payload = obj[msgtype] as any[];
  switch (msgtype) {
    case ServerMessageCode.Hello:
      return {
        type: "Hello",
        server_name: payload[0],
        protocol_ver: payload[1],
      };
    case ServerMessageCode.Error:
      return { type: "Error", error_msg: payload[0] };
  }
}

export function encode(data: ClientMessage) {
  switch (data.type) {
    case "Hello":
      return encodeMP({ Hello: [] });
  }
}

export default {
  Hello: () => encode({ type: "Hello" }),
};
