package be.kdg.labyrinth.JavaFX.model;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class LabyrinthModel {
    private char[][] labyrinth;

    public LabyrinthModel(String csvFile) {
        this.labyrinth = loadLabyrinthFromCSV(csvFile);
    }

    private char[][] loadLabyrinthFromCSV(String csvFile) {
        char[][] labyrinth = null;
        try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
            String line;
            int rowCount = 0;

            // Bepaal het aantal rijen
            while ((line = br.readLine()) != null) {
                rowCount++;
            }

            // Herinitialiseer de BufferedReader
            br.close();

            // Laad het doolhof
            try (BufferedReader br2 = new BufferedReader(new FileReader(csvFile))) {
                labyrinth = new char[rowCount][];
                int rowIndex = 0;

                while ((line = br2.readLine()) != null) {
                    // Verwijder alle komma's en spaties
                    String cleanedLine = line.replace(",", "").replace(" ", "");
                    labyrinth[rowIndex] = cleanedLine.toCharArray();
                    rowIndex++;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return labyrinth;
    }

    public char[][] getLabyrinth() {
        return labyrinth;
    }

    public int findStartRow() {
        for (int row = 0; row < labyrinth.length; row++) {
            for (int col = 0; col < labyrinth[row].length; col++) {
                if (labyrinth[row][col] == 'S') {
                    return row;
                }
            }
        }
        return -1;  // Geen startpunt gevonden
    }

    public int findStartCol(int startRow) {
        for (int col = 0; col < labyrinth[0].length; col++) {
            if (labyrinth[startRow][col] == 'S') {
                return col;
            }
        }
        return -1;  // Geen startpunt gevonden
    }
}