package de.nanoleaf.games.tictactoe;

import java.util.ArrayList;
import java.util.List;

public class CheckTicTacToe {
	
	private class Fields {
		
		List<Integer> fieldsList = null;
		


		
		public List<Integer> getFieldsList() {
			return fieldsList;
		}




		public Fields(int field1, int field2, int field3) {
			fieldsList = new ArrayList<Integer>();
			fieldsList.add(field1);
			fieldsList.add(field2);
			fieldsList.add(field3);
		}
	}

	List<Fields> m_checkList = null;
	public List<Fields> getCheckList() { 
		if (m_checkList == null) {
			m_checkList = new ArrayList<Fields>();
		}
		return m_checkList; 
	}


	public CheckTicTacToe() {
		initCheckList();
	}


	private void initCheckList() {
		
		/**
		 * ###
		 * ###
		 * ###
		 * 
		 */
		
		getCheckList().add(new Fields(1, 2, 3));
		getCheckList().add(new Fields(4, 5, 6));
		getCheckList().add(new Fields(7, 8, 9));
		
		getCheckList().add(new Fields(1, 4, 7));
		getCheckList().add(new Fields(2, 5, 6));
		getCheckList().add(new Fields(3, 6, 9));
		
		getCheckList().add(new Fields(1, 5, 9));
		getCheckList().add(new Fields(3, 5, 7));
		
	}


	public boolean checkFinal(int[] playerArray) {
		
		boolean finish = false;
		Integer playerlast = 0;
		boolean next = false;
		//System.out.println("Start Check...");
		List<Integer> playerList = new ArrayList<Integer>();
		for (Fields fields: getCheckList()) {
			next = false;
			finish = false;
			playerList = new ArrayList<Integer>();
			//System.out.println("List: " + fields.getFieldsList().toString());
			for (int f = 0; f < fields.getFieldsList().size(); f++) {
				int field = fields.getFieldsList().get(f).intValue();
				
				int player = playerArray[field];
				//System.out.println("Find Player: " + player);
				if (player == 0) {
					next = true;
					finish = false;
					//System.out.println("NEXT");
				} else {
					if (f == 0) {
						playerlast = player;
						playerList.add(playerlast);
					} else {
						if (playerlast == player) {
							playerList.add(playerlast);
						} else {
							next = true;
						}
							
					}
				}
				
				if (next) {
					break;
				}
				
			}
			if (next == false) {
				//System.out.println("FINISH");
				finish = true;
				//System.out.println("List: " + fields.getFieldsList().toString());
				break;
			}
		}
		
		
		return finish;
	}

}
