import { UnoSession } from '../gameLogic/UnoSession.js';
import { mkstring } from '../util/token.js';
import WebSocket from 'ws';

export interface UnoLobbyProperties {
    serverName: string;
    startcards: number;

}

export interface UnoLobbyElement {
    session?: UnoSession;
    sessionID: string;
    properties: UnoLobbyProperties;
    
}

export class UnoLobby {

    sessions: UnoLobbyElement[];

    constructor(){
        this.sessions = []
        setInterval(()=>{
            this.sessions = this.sessions.filter(el => !el.session.canDelete)
        },500)
    }

    public createLobby(properties: UnoLobbyProperties){
        const sId: string = mkstring(30);
        this.sessions.push({
            sessionID: sId,
            properties: properties,
            session: new UnoSession(sId,properties)
        })
        return sId;
    }

    public getLobbies(){
        let list = [ ];
        this.sessions.forEach(el => {
            list.push({
                id: el.sessionID,
                properties: el.properties,
                status: el.session.started,
                players: [...el.session.players, ...el.session.winners].length
            })
        })
        return list;
    }

    public joinLobby(nickname: string, lobbyId: string){
        let returnval = [false,"Die Lobby wurde nicht gefunden."]
        this.sessions.forEach(el => {
            console.log(el.sessionID, lobbyId)
            if(el.sessionID == lobbyId){
                returnval = el.session.playerJoin(nickname);
                console.log("found",returnval)
            }
        })
        console.log("done",returnval)
        return returnval;
     
        //
    }

    public registerLobby(message: string, ws: WebSocket){
        const command = JSON.parse(message);
        this.sessions.forEach(el => {
            if(el.sessionID == command.lobby){
                console.log("found session for " + command.id + " @ " + command.lobby )
                el.session.register_socket(ws,command.id);
            }
        })
    }
}