import { QueryRunner } from 'typeorm';

export class SessionRunnerSystem {
    pendingRunners: {
        player: PlayerMp;
        runner: QueryRunner;
    }[] = [];

    constructor() {
        mp.events.add('playerQuit', this.playerQuit.bind(this));
    }

    register(player: PlayerMp, runner: QueryRunner): void {
        this.pendingRunners.push({ player, runner });
        console.log(`Registered runner for ${player.name}`);
    }

    unregister(player: PlayerMp, runner: QueryRunner): void {
        this.pendingRunners = this.pendingRunners.filter((pr) => !(pr.player === player && pr.runner === runner));
        console.log('unregistering runner');
    }

    playerQuit(player: PlayerMp): void {
        const playerRunners = this.pendingRunners.filter((entry) => entry.player === player);
        this.pendingRunners = this.pendingRunners.filter((entry) => entry.player !== player);

        playerRunners.forEach((pendingRunner) => {
            if (pendingRunner.runner.isTransactionActive) {
                pendingRunner.runner.rollbackTransaction();
            }

            if (!pendingRunner.runner.isReleased) {
                pendingRunner.runner.release();
            }

            console.log('removing runner on quit');
        });
    }
}

export const sessionRunnerSystem = new SessionRunnerSystem();
