package org.academiadecodigo.bootcamp11.guessinggame;

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */
public class Player {
    private String name;
    private int maxTries;

    public Player(String name) {
        this.name = name;
    }

    public Player(String name, int maxTries) {
        this.name = name;
        this.maxTries = maxTries;
    }

    public String getName() {
        return this.name;
    }

    public int guessNumber(int max, Room room) {
        int guess = Utils.giveNumber(max);
        while (room.wasGuessed(guess)) {
            guess = Utils.giveNumber(max);
        }
        System.out.println("\t" + this.name + ": is it the number " +
                guess + "?");

        room.addGuess(guess);
        this.maxTries--;

        return guess;
    }

    public boolean canPlay() {
        return this.maxTries > 0;
    }

    public static Player[] fillPlayers(int numPlayers,
                                       String[] namePool,
                                       int maxTries) {
        if (namePool == null) {
            namePool = new String[] { "Zé" };
            numPlayers = 1;
        } else if (numPlayers > namePool.length) {
            // limit max players to available names
            numPlayers = namePool.length;
        } else if (numPlayers < 1) {
            numPlayers = 1;
        }

        namePool = shuffleNames(namePool);
        System.out.println("We have " + numPlayers + " player(s). " +
                "Let's set them up.");
        Player[] result = new Player[numPlayers];
        for (int i = 0; i < result.length; i++) {
            result[i] = new Player(namePool[i], maxTries);
        }

        showPlayers(result);

        return result;
    }

    private static String[] shuffleNames(String[] names) {
        String[] result = copyArray(names);
        // Fisher and Yates' method
        for (int i = 0; i < names.length-1; i++) {
            int roll = (int) Math.floor(Math.random() * (names.length-i)) + i;
            swap(result, i, roll);
        }
        return result;
    }

    private static void showPlayers(Player[] players) {
        for (int i = 0; i<players.length; i++) {
            System.out.printf("%-8s is Player %d\n",
                    players[i].getName(),
                    i+1);
        }
    }

    private static String[] copyArray(String[] array) {
        String[] result = new String[array.length];
        for (int i = 0; i < array.length; i++) {
            result[i] = array[i];
        }
        return result;
    }

    private static void swap(String[] array, int left, int right) {
        String temp = array[left];
        array[left] = array[right];
        array[right] = temp;
    }
}
