﻿using System.Linq;
using Gamelogic.AbstractStrategy.Grids;
using Gamelogic.Grids;

namespace Gamelogic.AbstractStrategy.Examples
{
	public class CustomVictoryRule : VictoryRules<RectPoint, GridGamePieceSettings>
	{
		protected override void CheckVictory()
		{
			var currentPlayer = game.CurrentPlayer;
			var currentState = game.State;
			int pieceCount = 1;

			foreach (var point in currentState.GetAllPoints())
			{
				if (!currentState.Contains(point))
					continue;

				var cell = currentState.GetPiecesAtPoint(point);

				if (cell.IsEmpty())
					continue;

				var testPiece = cell.FirstOrDefault();

				if (testPiece == null)
					continue;

				if (testPiece.playerID != currentPlayer.PlayerID)
					continue;

				var neighbourPoints = currentState.GetNeighboursOfPoint(point);

				foreach (var neighbourPoint in neighbourPoints)
				{
					if (!currentState.Contains(neighbourPoint))
						continue;

					var neighbourPiece = currentState.GetPiecesAtPoint(neighbourPoint).FirstOrDefault();

					if (neighbourPiece == null)
						continue;

					if (neighbourPiece.playerID == currentPlayer.PlayerID)
						pieceCount++;
				}

				if (pieceCount >= 4)
				{
					currentPlayer.SetVictoryState(VictoryType.Victory);
				}
				else
				{
					pieceCount = 1;
				}
			}
		}
	}
}