import java.io.*;
import java.net.*;
import java.util.logging.*;

public class ClientHandler implements Runnable {
    private static final Logger logger = Logger.getLogger(ClientHandler.class.getName());
    private Socket client;
    private BufferedReader in;
    private PrintWriter out;
    private Player player;
    private Room currentRoom;

    public ClientHandler(Socket client) {
        this.client = client;
    }

    @Override
    public void run() {
        try {
            in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            out = new PrintWriter(client.getOutputStream(), true);

            // Player setup
            out.println("Welcome to PiMud! Enter your name:");
            String playerName = in.readLine();
            player = new Player(playerName);
            out.println("Hello, " + playerName + "! Type 'help' for a list of commands.");

            currentRoom = PiMudServer.getStartingRoom(); // Set current room to starting room

            String command;
            while ((command = in.readLine()) != null) {
                handleCommand(command); // Handle each command
            }
        } catch (IOException e) {
            logger.severe("IOException occurred: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                client.close();
                logger.info("Client disconnected.");
            } catch (IOException e) {
                logger.severe("Error closing client connection: " + e.getMessage());
            }
        }
    }

   
    private void handleCommand(String command) {
    // Convert command to lowercase for case-insensitive comparison
    command = command.trim().toLowerCase();

    // Log the command received to the server console
    System.out.println("Received command: " + command);

    if (command.equals("look")) {
        out.println("You are in: " + currentRoom.getDescription());
        out.println("Exits: " + currentRoom.getExits());
        System.out.println("Executed 'look' command in room: " + currentRoom.getDescription());
    } else if (command.equals("help")) {
        out.println("Commands: look, move [direction], quit");
        System.out.println("Executed 'help' command.");
    } else if (command.equals("quit")) {
        out.println("Goodbye!");
        try {
            client.close();
            System.out.println("Client disconnected.");
        } catch (IOException e) {
            System.err.println("Error closing client connection: " + e.getMessage());
        }
    } else if (command.startsWith("move")) {
        // Handle 'move' commands
        if (currentRoom.getExits().contains("north") && command.contains("north")) {
            moveToRoom("north");
            System.out.println("Player moved north.");
        } else if (currentRoom.getExits().contains("south") && command.contains("south")) {
            moveToRoom("south");
            System.out.println("Player moved south.");
        } else if (currentRoom.getExits().contains("east") && command.contains("east")) {
            moveToRoom("east");
            System.out.println("Player moved east.");
        } else if (currentRoom.getExits().contains("west") && command.contains("west")) {
            moveToRoom("west");
            System.out.println("Player moved west.");
        } else {
            out.println("Unknown direction. Available directions: north, south, east, west.");
            System.out.println("Invalid direction attempted: " + command);
        }
    } else {
        out.println("Unknown command. Type 'help' for a list of commands.");
        System.out.println("Unknown command received: " + command);
    }
}


    private void moveToRoom(String direction) {
        Room newRoom = currentRoom.getExit(direction);
        if (newRoom != null) {
            currentRoom = newRoom;
            out.println("You move " + direction + ".");
            out.println("You are now in: " + currentRoom.getDescription());
            out.println("Exits: " + currentRoom.getExits());
            logger.info("Moved player to room: " + currentRoom.getDescription());
        } else {
            out.println("There is no exit in that direction.");
            logger.warning("Failed move attempt in direction: " + direction);
        }
    }

    public void sendMessage(String message) {
        out.println(message);
    }
}

