import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SudokuButtonListener implements ActionListener {
    private int row;
    private int col;
    private Sudoku sudoku;
    private JButton[][] buttons;

    public SudokuButtonListener(int row, int col, Sudoku sudoku, JButton[][] buttons) {
        this.row = row;
        this.col = col;
        this.sudoku = sudoku;
        this.buttons = buttons;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String input = JOptionPane.showInputDialog("Entrez un nombre :");
        if (input != null && input.length() > 0) {
            try {
                int num = Integer.parseInt(input);
                sudoku.getGrid().getCell(row, col).setValue(num);
                if (num == 0) {
                    buttons[row][col].setText(""); // Case vide si le nombre est 0
                } else {
                    buttons[row][col].setText(String.valueOf(num));
                }
                if (!isValid(num, row, col)) {
                    buttons[row][col].setForeground(Color.RED); // Met le texte en rouge en cas de mouvement invalide
                } else {
                    buttons[row][col].setForeground(Color.BLACK); // Réinitialise la couleur du texte
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "Veuillez entrer un nombre valide.");
            }
        }
    }

    private boolean isValid(int num, int row, int col) {
        return isValidRow(num, row) && isValidCol(num, col) && isValidBox(num, row - row % 3, col - col % 3);
    }

    private boolean isValidRow(int num, int row) {
        for (int i = 0; i < 9; i++) {
            if (sudoku.getGrid().getCell(row, i).getValue() == num && i != col) {
                return false;
            }
        }
        return true;
    }

    private boolean isValidCol(int num, int col) {
        for (int i = 0; i < 9; i++) {
            if (sudoku.getGrid().getCell(i, col).getValue() == num && i != row) {
                return false;
            }
        }
        return true;
    }

    private boolean isValidBox(int num, int boxStartRow, int boxStartCol) {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                int row = i + boxStartRow;
                int col = j + boxStartCol;
                if (sudoku.getGrid().getCell(row, col).getValue() == num && (row != this.row || col != this.col)) {
                    return false;
                }
            }
        }
        return true;
    }
}