import java.util.Random;

/**
 * Reprezentacja sześciokąta z rurami {@link Hexelem}
 * 
 *  
 */
public final class Hex{
	/**Tablica Hexelemów*/
	public Hexelem[] elems = new Hexelem[3];
	/**ilość elemntów {@link Hexelem}*/
	public int numofpipes;
	
	/**
	 * Konstruktor tworzący losowy element
	 */
	public Hex(){
		Random rand = new Random();
		numofpipes = rand.nextInt(3)+1;
		boolean[] checked = new boolean[6];
		for (boolean b : checked)
			b = false;
		
		
		for (int i=0; i<numofpipes; i++){
			int k, l;
			do
				k=rand.nextInt(6);
			while (checked[k]);   //czy nie zajęte
			checked[k]=true;
			do
				l=rand.nextInt(6);
			while (checked[l] || k==l);
			checked[l]=true;
			
			elems[i] = new Hexelem(k,l);
		}
	}
	
	/**
	 * Konstruktor elementu o danym wlocie
	 * @param input numer krawędzi wlotowej
	 */
	public Hex(int input){
		Random rand = new Random();
		int numofpipes = rand.nextInt(3)+1;
		boolean[] checked = new boolean[6];
		int m;
		for (boolean b : checked)
			b = false;
		
		checked[input] = true;
		do
			m = rand.nextInt(6);
		while(checked[m]);
		checked[m] = true;
		elems[0] = new Hexelem(input, m);
		
		for (int i=1; i<numofpipes; i++){
			int k, l;
			do
				k=rand.nextInt(6);
			while (checked[k]);   //czy nie zajęte
			checked[k]=true;
			do
				l=rand.nextInt(6);
			while (checked[l] || k==l);
			checked[l]=true;
			
			elems[i] = new Hexelem(k,l);
		}
	}
	/**
	 * Konstruktor elementów specjalnych
	 * @param kind rodzaj
	 */
	public Hex(String kind){
		elems = new Hexelem[1];
		
		elems[0] = new Hexelem(kind);
	}
	
	public void rotate(){
		for (Hexelem h : elems){
			if (h == null)
				break;
			if (h.full > 0)
				return;
		}
		
		for (Hexelem h : elems){
			if (h == null)
				break;
			h.rotate();
		}
	}	
	
	/**
	 * Dolewanie wody
	 * wywoływane przez {@link Water}
	 * @param input numer krawędzi wlotowej
	 * @return input jeśli element niewypełniony do końca w przeciwnym wypadku numer krawędzi wylotowej, -1 w przypadku błędu
	 */
	public int pour(int input){
		boolean check;
		
		for (Hexelem h : elems){
			if (h.input == input){
				check = h.pour(h.input);
				if(check)
					return input;
				return h.output;
			}
			if (h.output == input){
				check = h.pour(h.output);
				if(check)
					return input;
				return h.output;
			}		
		}
		return -1;
	}	
}
