package eu.jonahbauer.wizard.core;

import eu.jonahbauer.wizard.common.messages.player.PickTrumpMessage;
import eu.jonahbauer.wizard.common.messages.player.PlayCardMessage;
import eu.jonahbauer.wizard.common.messages.player.PredictMessage;
import eu.jonahbauer.wizard.common.model.Card;
import eu.jonahbauer.wizard.core.machine.Game;
import eu.jonahbauer.wizard.core.messages.Observer;
import eu.jonahbauer.wizard.core.model.GameConfiguration;
import eu.jonahbauer.wizard.core.model.Configurations;

import java.util.List;
import java.util.Scanner;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CLI {
    public static void main(String[] args) {
        GameConfiguration config = Configurations.DEFAULT;
        Observer observer = (player, msg) -> System.out.println(msg);
        Game game = new Game(config, observer);
        var players = List.of(
                UUID.randomUUID(),
                UUID.randomUUID(),
                UUID.randomUUID(),
                UUID.randomUUID()
        );

        game.start(players);

        Scanner scanner = new Scanner(System.in);
        Pattern pattern = Pattern.compile("(\\d) ([a-z]+) (.*)");
        while (scanner.hasNextLine()) {
            try {
                Matcher matcher = pattern.matcher(scanner.nextLine());
                if (!matcher.find()) {
                    System.err.println("Format is \"(\\d) ([a-z]+) (.*)\"");
                    continue;
                }
                String player = matcher.group(1);
                String command = matcher.group(2);
                String param = matcher.group(3);

                int id = Integer.parseInt(player);

                if (id > players.size()) {
                    System.err.println("ID must be between 0 and " + (players.size() - 1));
                    continue;
                }

                switch (command) {
                    case "predict" -> {
                        int prediction = Integer.parseInt(param);
                        game.onMessage(players.get(id), new PredictMessage(prediction));
                    }
                    case "play" -> {
                        Card card = Card.valueOf(param);
                        game.onMessage(players.get(id), new PlayCardMessage(card));
                    }
                    case "trump" -> {
                        Card.Suit suit = Card.Suit.valueOf(param);
                        game.onMessage(players.get(id), new PickTrumpMessage(suit));
                    }
                    default -> System.err.println("Unknown command: " + command);
                }
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
        }
    }
}
