import WebSocket from 'ws';
import { UnoSession, UnoPlayer } from './UnoSession';

export interface UIVoteQuestion {
    question: string;
    options: string[];
    counter?: number[];
}

export class UIVote {
    duration: number;
    questions: UIVoteQuestion[];
    game: UnoSession;
    title: string;
    votedPlayers: String[];
    stopTimer;

    constructor(game: UnoSession, title:string, duration: number){
        this.duration = duration;
        this.game = game;
        this.title = title;
        this.questions = [];
        this.stopTimer = undefined;
        this.votedPlayers = [];
    }

    public addQuestion(question: string, options: string[]){
        let countArray = [];
        options.forEach(el => countArray.push(0));
        this.questions.push({
            question: question,
            options: options,
            counter: countArray,
        })
    }

    public startVote(callback){
        [...this.game.players, ...this.game.winners].forEach(el =>{
            if (el.socket && el.socket?.OPEN){
                el.socket.send(JSON.stringify({
                    "vote": this.title,
                    "questions":this.questions,
                    "time": this.duration
                }))
            }
        })
        this.stopTimer = setTimeout(()=>this.endVote(callback), this.duration);
    }

    private endVote(callback){
        [...this.game.players, ...this.game.winners].forEach(el =>{
            if (el.socket && el.socket?.OPEN){
                el.socket.send(JSON.stringify({"endvote":""}))
            }
        })
        callback(this.questions);
    }

    private broadcastResults(){
        [...this.game.players, ...this.game.winners].forEach(el =>{
            if (el.socket && el.socket?.OPEN){
                el.socket.send(JSON.stringify({"voteres":this.questions}))
            }
        })
    }

    public abortVote(){
        clearTimeout(this.stopTimer);
        [...this.game.players, ...this.game.winners].forEach(el =>{
            if (el.socket && el.socket?.OPEN){
                el.socket.send(JSON.stringify({"endvote":""}))
            }
        })
    }

    public voteEvent(id,player:UnoPlayer){
        if (this.votedPlayers.filter(el => el == player.userId).length == 0){
            this.questions[0].counter[id - 1] ++;
            this.broadcastResults();
            player.socket.send(JSON.stringify({
                notify: "Stimme abgegeben",
                warning: true,
            }))
            this.votedPlayers.push(player.userId)
        }else{
            player.socket.send(JSON.stringify({
                notify: "Stimme bereits abgegeben",
                warning: false,
            }))
        }
    }


}