/* 
    This file is a part of the SteamWar software.
    
    Copyright (C) 2020  SteamWar.de-Serverteam

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

package de.steamwar.velocitycore.listeners;

import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.PostLoginEvent;
import de.steamwar.velocitycore.Config;
import de.steamwar.velocitycore.VelocityCore;
import de.steamwar.command.TypeValidator;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.Message;
import de.steamwar.sql.PollAnswer;
import net.kyori.adventure.text.event.ClickEvent;

public class PollSystem extends BasicListener {

    public static void init() {
        poll = VelocityCore.get().getConfig().getPoll();
        if(poll == null)
            return;

        if(noCurrentPoll())
            return;

        PollAnswer.setCurrentPoll(poll.getQuestion());
        new PollSystem();
    }

    private static Config.Poll poll = null;


    @Subscribe
    public void onPostLogin(PostLoginEvent event){
        Chatter player = Chatter.of(event.getPlayer());

        PollAnswer answer = PollAnswer.get(player.user().getId());
        if(answer.hasAnswered())
            return;

        sendPoll(player);
    }

    public static void sendPoll(Chatter player) {
        player.system("POLL_HEADER");
        player.prefixless("POLL_HEADER2");
        player.prefixless("POLL_QUESTION", poll.getQuestion());

        for(int i = 1; i <= poll.getAnswers().size(); i++) {
            player.prefixless("POLL_ANSWER", new Message("POLL_ANSWER_HOVER", poll.getAnswers().get(i-1)), ClickEvent.runCommand("/poll " + i), poll.getAnswers().get(i-1));
        }
    }

    private static boolean noCurrentPoll(){
        return poll == null;
    }

    public static TypeValidator<Chatter> noPoll() {
        return (sender, value, messageSender) -> {
            if (PollSystem.noCurrentPoll()) {
                messageSender.send("POLL_NO_POLL");
                return false;
            }
            return true;
        };
    }

    public static int answers(){
        return poll.getAnswers().size();
    }

    public static String getAnswer(int i) {
        return poll.getAnswers().get(i);
    }
}
