import { RTMT } from "../rtmt/rtmt";
import { MatchMaker, OnPlayersPaired } from "./MatchMaker";

export class MatchMakerImpl implements MatchMaker {
    private waitingPlayerId?: string;

    private onPlayersPaired?: OnPlayersPaired;

    private rtmt: RTMT;

    constructor(params: { rtmt: RTMT }) {
        this.rtmt = params.rtmt;
    }

    private fireOnPlayerPaired(player1Id: string, player2Id: string): void {
        this.onPlayersPaired?.(player1Id, player2Id)
    }

    private setWaitingPlayerId(playerKey?: string) {
        this.waitingPlayerId = playerKey;
    }

    public join(newcomerPlayerId: string): void {
        if (this.waitingPlayerId === newcomerPlayerId) return;
        if (this.waitingPlayerId && this.rtmt.isClientOnline(this.waitingPlayerId)) {
            this.fireOnPlayerPaired(this.waitingPlayerId, newcomerPlayerId)
            this.setWaitingPlayerId(undefined);
        } else {
            this.waitingPlayerId = newcomerPlayerId
        }
    }

    public cancel(playerId: string): boolean {
        if(playerId === this.waitingPlayerId) {
            this.waitingPlayerId = undefined;
            return true;
        }

        return false;
    }
    
    public listenOnPlayersPaired(onPlayersPaired: OnPlayersPaired): void {
        this.onPlayersPaired = onPlayersPaired;
    }
}