package be.kdg.labyrinth;

import java.util.Scanner;

public class Game {
    private Board board;
    private Player player;
    private Highscore highscore;
    private long starttime, endtime, totalTime;
    private static final String CSV_PATH = "src/be/kdg/labyrinth/Labyrinth.csv";

    public Game() {
        board = new Board(CSV_PATH);
        player = new Player(board.getStartRow(), board.getStartCol());
        highscore = new Highscore(); // Maak een highscore-object aan
    }

    public void start() {
        Scanner scanner = new Scanner(System.in);
        boolean opnieuwSpelen = true;

        while (opnieuwSpelen) {
            System.out.println("Welkom bij het Labyrinth");
            highscore.displayHighscores();  // Toon de huidige highscores
            board.printLabyrinth(player.getRow(), player.getCol());

            starttime = System.currentTimeMillis();

            while (true) {
                System.out.println("Gebruik z (omhoog), s (omlaag), q (links), d (rechts): ");
                String input = scanner.nextLine();

                switch (input) {
                    case "z" -> player.move(-1, 0, board);
                    case "s" -> player.move(1, 0, board);
                    case "q" -> player.move(0, -1, board);
                    case "d" -> player.move(0, 1, board);
                    default -> System.out.println("Foute invoer, gebruik: z, s, q, d");
                }
                board.printLabyrinth(player.getRow(), player.getCol());

                if (board.isExit(player.getRow(), player.getCol())) {
                    System.out.println("Je hebt gewonnen!");
                    endtime = System.currentTimeMillis();
                    totalTime = (endtime - starttime) / 1000;
                    System.out.println("Je hebt het labyrinth voltooid in: " + totalTime + " seconden");

                    highscore.addScore(totalTime);  // Voeg de score toe aan de highscores
                    highscore.displayHighscores();  // Toon de updated highscores
                    break;
                }
            }

            System.out.println("Wil je opnieuw spelen? (ja/nee)");
            String antwoord = scanner.nextLine().toLowerCase();

            if (antwoord.equals("nee")) {
                System.out.println("Bedankt voor het spelen!");
                opnieuwSpelen = false;
            } else {
                board = new Board(CSV_PATH);
                player = new Player(board.getStartRow(), board.getStartCol());
            }
        }
    }
}
