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

namespace Gamelogic.AbstractStrategy.Examples
{
	/// <summary>
	/// Extension to ordinary rules for basic draughts specific rules.
	/// </summary>
	/// <remarks>
	/// Implements British draughts rules:
	///  - Obligation to capture
	///  - Pieces can only capture forwards
	/// </remarks>
	public class BasicDraughtsRules : GridGameRules
	{
		public bool obligationToCapture = true;
		public bool multipleCaptureMoves = true;
		public bool advanceTurnOnEmptyMoveList = true;		

		/// <summary>
		/// Implement obligation to capture
		/// </summary>
		protected override void UpdateMovesForPlayer(List<GameMove<RectPoint, GridGamePieceSettings>> movesList, Player<RectPoint, GridGamePieceSettings> player)
		{
			base.UpdateMovesForPlayer(movesList, player);

			if (!obligationToCapture)
				return;

			// Check moves list for captures. If there are any, remove all other moves
			if (movesList.Any(t => t is CapturePieceMove))
			{
				movesList.RemoveAllBut(t => t is CapturePieceMove);
			}
		}

		/// <summary>
		/// If the piece that just did a capture has more capture options, then the turn does not end
		/// </summary>
		/// <param name="EndedMove"></param>
		protected override void OnMoveEnd(GameMove<RectPoint, GridGamePieceSettings> EndedMove)
		{
			base.OnMoveEnd(EndedMove);
			
			var moveList = GetValidMovesListForPlayer(game.TurnManager.CurrentPlayer);

			// Clear the list as a signal to OnAllMovesEnded
			moveList.Clear();

			if (!multipleCaptureMoves)
				return;

			// Any new capture moves to add?
			var captureMove = EndedMove as CapturePieceMove;
			if (captureMove != null && captureMove.Direction == MoveMode.Forward)
			{
				var pieceSettings = GetPieceSettings(captureMove.CapturingPiece);
				var gameState = game.State;

				foreach (var capture in pieceSettings.GetCaptures(gameState, captureMove.CapturingPiece, captureMove.DestinationPosition))
				{
					moveList.Add(gameState.CreateCapturePieceMove(captureMove.CapturingPiece, capture.piece, captureMove.DestinationPosition, capture.position,
						gameState.FindPiece(capture.piece)));
				}
			}
		}

		/// <summary>
		/// If the moves list is empty, then we can advance the game
		/// We take this beaviour away from the base by setting movesPerTurn to 0
		/// so that it does not automatically advance after every move
		/// </summary>
		protected override void OnAllMovesEnded()
		{
			base.OnAllMovesEnded();

			if (!advanceTurnOnEmptyMoveList)
				return;

			if (GetValidMovesListForPlayer(game.TurnManager.CurrentPlayer).IsEmpty())
			{
				game.TurnManager.AdvanceTurnState();
			}
		}
	}
}
