import Channel from "../channel.js";
import {
	cancelGame,
	gameReady,
	putMove,
} from "@/services/shogi/index.js";
import type { StreamMessages } from "../types.js";

export default class extends Channel {
	public readonly chName = "shogiGame";
	public static shouldShare = false;
	public static requireCredential = false;
	private gameId: string | null = null;

	constructor(id: string, connection: Channel["connection"]) {
		super(id, connection);
		this.onEvent = this.onEvent.bind(this);
	}

	public async init(params: any) {
		if (typeof params.gameId !== "string") return;
		this.gameId = params.gameId;
		this.subscriber.on(`shogiGameStream:${this.gameId}`, this.onEvent);
	}

	private onEvent(data: StreamMessages["shogiGame"]["payload"]) {
		this.send(data);
	}

	public onMessage(type: string, body: any) {
		if (!this.gameId) return;
		switch (type) {
			case "ready":
				if (this.user && typeof body === "boolean") gameReady(this.gameId, this.user, body);
				break;
			case "cancel":
				if (this.user) cancelGame(this.gameId, this.user);
				break;
			case "move":
				if (this.user && body && typeof body.usi === "string") {
					putMove(this.gameId, this.user, body.usi, typeof body.id === "string" ? body.id : null);
				}
				break;
		}
	}

	public dispose() {
		if (this.gameId) {
			this.subscriber.off(`shogiGameStream:${this.gameId}`, this.onEvent);
		}
	}
}
