using System.Collections.Generic;
using System.Linq;
using System.Windows.Media;
using Machinations.FromFlash.machinations.model;

namespace Machinations.Status
{
    public class PoolStatus : IElementStatus
    {
        //private readonly List<Resource> m_resources;
        private Dictionary<Color, int> m_resources2; 
        private readonly int m_shortage;
        private readonly Pool m_pool;
        private readonly int m_step;

        public PoolStatus(Pool pool, int step)
        {
            m_pool = pool;
            //m_resources = pool.Resources.CloneResources();
            m_resources2 = GetResources(pool.Resources);
            m_shortage = pool.Shotage;
            m_step = step;
        }

        private Dictionary<Color, int> GetResources(List<Resource> resources)
        {
            var colors = resources.Select(r => r.Color).Distinct().ToArray();
            return colors.ToDictionary(color => color, color => resources.Count(r => r.Color.Equals(color)));
        }

        public int Step { get { return m_step; } }

        public void Restore()
        {
            var res = new List<Resource>();
            foreach (var pair in m_resources2)
            {
                for (int i = 0; i < pair.Value; i++)
                {
                    res.Add(new Resource(pair.Key, 0));
                }
            }
            m_pool.Resources = res;
            //m_pool.Resources = m_resources.CloneResources();
            m_pool.Shotage = m_shortage;
            m_pool.OnChanged("Status restored");
        }

        public bool NeedNewStatus()
        {
            //return !m_resources.SequenceEqual(m_pool.Resources) || m_shortage != m_pool.Shotage;
            return !m_resources2.SequenceEqual(GetResources(m_pool.Resources)) || m_shortage != m_pool.Shotage;
        }
    }
}