package morpion;

import java.net.*;
import java.util.Random;

public class MorpionServeur {
    private char[] grille = new char[9];
    private Random rand = new Random();

    public MorpionServeur() {
        for (int i = 0; i < 9; i++) grille[i] = '.';
    }

    public static void main(String[] args) throws Exception {
        MorpionServeur jeu = new MorpionServeur();
        DatagramSocket socket = new DatagramSocket(5000);
        System.out.println("Serveur Morpion (IA Hasard) lancé sur le port 5000...");

        while (true) {
            byte[] buffer = new byte[256];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            socket.receive(packet);

            String input = new String(packet.getData(), 0, packet.getLength()).trim();
            int coupClient = Integer.parseInt(input);

            String status = "CONTINUE";

            // Tour du Joueur (X)
            if (coupClient >= 0 && coupClient < 9 && jeu.grille[coupClient] == '.') {
                jeu.grille[coupClient] = 'X';
                
                if (jeu.checkWin('X')) {
                    status = "WIN_PLAYER";
                } else if (jeu.estPleine()) {
                    status = "DRAW";
                } else {
                    // Tour du Serveur (O)
                    jeu.jouerIA();
                    if (jeu.checkWin('O')) {
                        status = "WIN_SERVER";
                    } else if (jeu.estPleine()) {
                        status = "DRAW";
                    }
                }
            }

            // Envoi de la grille + Status (Format: "GRILLE|STATUS")
            String reponse = new String(jeu.grille) + "|" + status;
            byte[] dataReponse = reponse.getBytes();
            socket.send(new DatagramPacket(dataReponse, dataReponse.length, packet.getAddress(), packet.getPort()));

            // Réinitialiser si fini
            if (!status.equals("CONTINUE")) {
                System.out.println("Partie terminée : " + status);
                jeu.reset();
            }
        }
    }

    private void jouerIA() {
        int choix;
        do { choix = rand.nextInt(9); } while (grille[choix] != '.');
        grille[choix] = 'O';
    }

    private boolean checkWin(char s) {
        int[][] wins = {{0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,5,8}, {0,4,8}, {2,4,6}};
        for (int[] w : wins) {
            if (grille[w[0]] == s && grille[w[1]] == s && grille[w[2]] == s) return true;
        }
        return false;
    }

    private boolean estPleine() {
        for (char c : grille) if (c == '.') return false;
        return true;
    }

    private void reset() {
        for (int i = 0; i < 9; i++) grille[i] = '.';
    }
}
