package eu.jonahbauer.wizard.core.machine.states.round;

import eu.jonahbauer.wizard.core.machine.states.GameData;
import eu.jonahbauer.wizard.core.machine.Game;
import eu.jonahbauer.wizard.core.machine.states.trick.StartingTrick;
import eu.jonahbauer.wizard.common.messages.observer.PredictionMessage;
import eu.jonahbauer.wizard.common.messages.observer.UserInputMessage;
import eu.jonahbauer.wizard.common.messages.player.PlayerMessage;
import eu.jonahbauer.wizard.common.messages.player.PredictMessage;
import lombok.Getter;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static eu.jonahbauer.wizard.core.machine.states.GameData.*;
import static eu.jonahbauer.wizard.common.messages.observer.UserInputMessage.Action.MAKE_PREDICTION;

@Getter
public final class Predicting extends RoundState {
    public Predicting(GameData data) {
        super(data.requireEach(PLAYERS, HANDS).require(PREDICTIONS, TRUMP_SUIT, CURRENT_PLAYER));
    }

    @Override
    public void onEnter(Game game) {
        game.notify(new UserInputMessage(get(CURRENT_PLAYER), MAKE_PREDICTION, getTimeout(game, true)));
        timeout(game);
    }

    @Override
    public void onTimeout(Game game) {
        try {
            checkPrediction(game, 0);
            transition(game, 0);
        } catch (IllegalArgumentException e) {
            try {
                checkPrediction(game, 1);
                transition(game, 1);
            } catch (IllegalArgumentException e2) {
                throw new AssertionError(e2);
            }
        }
    }

    @Override
    public void onMessage(Game game, UUID player, PlayerMessage message) {
        if (get(CURRENT_PLAYER).equals(player) && message instanceof PredictMessage predictMessage) {
            checkPrediction(game, predictMessage.getPrediction());
            transition(game, predictMessage.getPrediction());
        } else {
            super.onMessage(game, player, message);
        }
    }

    private void checkPrediction(Game game, int prediction) {
        int round = get(ROUND);
        if (prediction < 0 || prediction > round + 1) {
            throw new IllegalArgumentException("Prediction must be between 0 and " + (round + 1) + ".");
        }

        if (!game.getConfig().allowExactPredictions() && isLastPlayer()) {
            int sum = get(PREDICTIONS).values().stream().mapToInt(i -> i).sum();
            if (sum + prediction == round + 1) {
                throw new IllegalArgumentException("Predictions must not add up.");
            }
        }
    }

    private void transition(Game game, int prediction) {
        game.notify(new PredictionMessage(get(CURRENT_PLAYER), prediction));

        // add prediction
        var predictions = new HashMap<>(get(PREDICTIONS));
        predictions.put(get(CURRENT_PLAYER), prediction);

        GameData data = getData().with(
                PREDICTIONS, Map.copyOf(predictions),
                CURRENT_PLAYER, getNextPlayer()
        );

        if (isLastPlayer()) {
            transition(game, new StartingTrick(data));
        } else {
            transition(game, new Predicting(data));
        }
    }

    private boolean isLastPlayer() {
        return getDealer().equals(get(CURRENT_PLAYER));
    }
}
