package at.priv.graf.georg.sudokusolv;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;

public class Box {

    private final HashSet<Integer> possibilities;

    // Constructor of un-initialized, open Box
    public Box() {
        possibilities = new HashSet<>();
        for (int i = 1; i <= 9; i++) {
            possibilities.add(i);
        }
    }

    // Constructor for fixed Box
    public Box(int i) {
        possibilities = new HashSet<>();
        possibilities.add(i);
    }

    public int getValue() {
        if (possibilities.size() != 1) {
            throw new IllegalStateException("There are more than one possibilities left!");
        }
        return (int) possibilities.toArray()[0];
    }

    public HashSet<Integer> getPossibilities() {
        return possibilities;
    }

    public ArrayList<Integer> getPossibilitiesCopy() {
        return new ArrayList<>(getPossibilities());
    }


    public void removePossibility(int i) throws IllegalBoxState {
        if (possibilities.remove(i)) {  // true if set is now smaller, "i" was in it
            if (possibilities.isEmpty()) {
                throw new IllegalBoxState("Removed last possibility");
            }
        } // else number was not anymore in list
    }

    public boolean isFix() {
        return possibilities.size() == 1;
    }

    public String toString() {
        if (isFix()) return String.format("%s", getValue());
        else {
            StringBuilder rc = new StringBuilder("\\");
            Object[] sortedList = possibilities.toArray();
            Arrays.sort(sortedList);
            for (Object boxValue : sortedList) rc.append(String.format("%d", (int) boxValue));
            rc.append("/");
            return rc.toString();
        }
    }

}
