package org.academiadecodigo.bootcamp11.guessinggame;

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */
public class Room {
    // This class will contain the guesses of all the players
    private int[] triedNumbers;

    public void addGuess(int number) {
        int[] array = this.triedNumbers;
        int length = (array != null && array.length > 0) ?
                array.length : 0;
        int[] result = new int[length + 1];
        for (int i = 0; i < length; i++) {
            result[i] = array[i];
        }
        result[length] = number;
        this.triedNumbers = result;
    }

    public boolean wasGuessed(int number) {
        if (this.triedNumbers == null) {
            return false;
        }
        for (int i = 0; i < this.triedNumbers.length; i++) {
            if (this.triedNumbers[i] == number) {
                return true;
            }
        }
        return false;
    }

    public String toString() {
        String result = "[";
        if (this.triedNumbers == null || this.triedNumbers.length == 0) {
            return result + "]";
        }
        int[] triedNumbers = bubbleSort(this.triedNumbers);
        int length = triedNumbers.length;
        for (int i = 0; i < (length - 1); i++) {
            result += triedNumbers[i] + ", ";
        }
        return result + triedNumbers[length - 1] + "]";
    }

    private int[] bubbleSort(int[] array) {
        int[] result = copyArray(array);
        boolean anychange = true;
        while (anychange) {
            anychange = false;
            for (int i=0; i<result.length-1; i++) {
                if(result[i+1] < result[i]) {
                    swap(result, i, i+1);
                    anychange = true;
                }
            }
        }
        return result;
    }

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

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