import { UnoSession, UnoCard, UnoPlayer, } from './UnoSession.js';
import { processUiEvents } from './UiEvents.js'
import * as Log from './../util/logging.js'
import WebSocket from 'ws';

export class UnoSockets {
    private game:UnoSession;
    pingTimer;

    constructor(game) {
        //heatbeat
        this.game = game;
        this.pingTimer = setInterval(()=>{
            this.game.players.forEach(el => {
                if(el.socket){
                    el.socket.send(JSON.stringify({
                        heartbeat: true
                    }))
                }
            })
        },10000) 

    }

    public register_socket(socket: WebSocket, id: string){
        let valid: boolean = false;
        this.game.players.forEach((obj, ix) => {
            if (obj.userId == id) {
                console.log('registered socket fot ',obj.userId);
                obj.socket = socket;
                obj.socket.on('message', (message: string) => {
                    console.log('received message form:',obj.userId,'data', message);
                    const command = JSON.parse(message);
                    this.processCommand(command,obj);
                });
                valid = true;
            }
        });
        this.game.winners.forEach((obj, ix) => {
            if (obj.userId == id) {
                console.log('registered socket fot ',obj.userId);
                obj.socket = socket;
                obj.socket.on('message', (message: string) => {
                    console.log('received message form:',obj.userId,'data', message);
                    const command = JSON.parse(message);
                    this.processCommand(command,obj);
                });
                valid = true;
            }
        });
        if (!valid){
            socket.send(JSON.stringify({kick:"Ungültige session."}));
        }
    }

    private processCommand(command: any, player: UnoPlayer){
        switch(command.action){
            case 'uibutton':
                processUiEvents(this.game,player,command)
                break;
            case 'initData':
                this.game.initClient(player);
                break;
            case 'heartbeat':
                this.game.clientHearbeat(player);
                break;
            default:
                //none
        }
        if (command.vote){
            if(this.game.activeVote){this.game.activeVote.voteEvent(command.vote, player)}
        }
    }
}