using System;
using System.Collections.Generic;
using TheGameExtreme.model.card;
using TheGameExtreme.model.piles;

namespace TheGameExtreme.model.gameActions.classic
{
    public class JouerUneCarte : GameAction
    {

        public Card OldCard { get; set; }


        public JouerUneCarte(Piles ListOrderedStacks) : base(ListOrderedStacks)
        {
        }

        public bool play(decimal valueCard, List<Card> CurrentHand, int orderedStackSelected, Player player, List<Card> CurrentCardPlayed)
        {
            foreach (Card card in CurrentHand)
            {
                if (valueCard.CompareTo(card.Value) == 0)
                {
                    if (orderedStackSelected >= 0 && orderedStackSelected < ListOrderedStacks.Size)
                    {
                        bool success;
                        if (orderedStackSelected < (ListOrderedStacks.Size * 0.5))
                        {
                            ErrorMessage = null;
                            success = rule(card, ListOrderedStacks.getStack(orderedStackSelected), true, player, CurrentCardPlayed);
                        }
                        else
                        {
                            ErrorMessage = null;
                            success = rule(card, ListOrderedStacks.getStack(orderedStackSelected), false, player, CurrentCardPlayed);
                        }
                        if (success)
                        {
                            CurrentHand.Remove(card);
                        }
                        return success;
                    }
                    else
                    {
                        ErrorMessage = AppRessource.StrCantGetStack;
                    }
                }
            }
            ErrorMessage = AppRessource.StrCardDoesntExist;
            return false;
        }

        private bool rule(Card card, Stack<Card> stack, bool bottomUp, Player player, List<Card> CurrentCardPlayed)
        {
            if ((bottomUp && card.Value > stack.Peek().Value) || (!bottomUp && card.Value < stack.Peek().Value) || card.Value.CompareTo(stack.Peek().Value - 10) == 0 || card.Value.CompareTo(stack.Peek().Value + 10) == 0)
            {
                OldCard = stack.Peek();
                player.joue(card);
                CurrentCardPlayed.Add(card);
                stack.Push(card);
                return true;
            }
            else
            {
                ErrorMessage = AppRessource.StrWrongStack;
                return false;
            }
        }
    }
}
