import { BinaryStreamReader } from "../binary/readerStream";

export enum ReadKind {
  Connected = 0,
  Disconnected = 1,
  Moved = 2,
  StageChanged = 3,
  PeerConnectionChanged = 4,
  Offer = 5,
  Answer = 6,
  IceCandidate = 7,
}

export async function readEvent(reader: BinaryStreamReader) {
  const kind = await reader.readUInt8();
  switch (kind) {
    case ReadKind.Connected: {
      const id = await reader.readUInt32();
      const name = await reader.readFixedString(0x20);
      return { kind, id, name };
    }
    case ReadKind.Disconnected: {
      const id = await reader.readUInt32();
      return { kind, id };
    }
    case ReadKind.Moved: {
      const id = await reader.readUInt32();
      const position = await reader.readArray(3, async reader => reader.readFloat32());
      return { kind, id, position };
    }
    case ReadKind.StageChanged: {
      const id = await reader.readUInt32();
      const stage = await reader.readFixedString(0x40);
      return { kind, id, stage };
    }
    case ReadKind.PeerConnectionChanged: {
      const id = await reader.readFixedString(36);
      const connected = await reader.readBoolean();
      return { kind, id, connected };
    }
    case ReadKind.Offer: {
      const id = await reader.readFixedString(36);
      const offerSdp = await reader.readString(await reader.readUInt32());
      return { kind, id, offerSdp }
    }
    case ReadKind.Answer: {
      const id = await reader.readFixedString(36);
      const answerSdp = await reader.readString(await reader.readUInt32());
      return { kind, id, answerSdp }
    }
    case ReadKind.IceCandidate: {
      const id = await reader.readFixedString(36);
      const candidate: RTCIceCandidateInit = JSON.parse(await reader.readString(await reader.readUInt32()));
      return { kind, id, candidate }
    }
    default:
      throw new Error(`unsupported kind ${kind}`)
  }
}
