using System;
using System.Collections.Generic;

namespace ECOT.Engine.Statistics
{
    using PoolHash = Dictionary<string, List<Variable>>;

    public delegate void SimulationEventHandler(string pool, Simulation simulation);

    /// <summary>
    /// 
    /// </summary>
    public class Simulation
    {
        public event SimulationEventHandler OnBeforeFinished;
        public event SimulationEventHandler OnFinished;

        public void Register(string pool, Variable var)
        {
            if (!this.pools.ContainsKey(pool))
                this.pools[pool] = new List<Variable>();
            this.pools[pool].Add(var);
        }

        public void Unregister(string pool, Variable var)
        {
            if (!this.pools.ContainsKey(pool))
                throw new ArgumentOutOfRangeException();

            for (int i = 0; i < this.pools[pool].Count; i++)
            {
                if (this.pools[pool][i].Name == var.Name)
                {
                    this.pools[pool].RemoveAt(i);
                    return;
                }
            }
        }

        public Variable GetVariable(string pool, string name)
        {
            return this.pools[pool].Find(delegate(Variable var)
            {
                return var.Name.ToLower().Equals(name);
            });
        }

        public void Simulate(string pool)
        {
            // Définit toutes les variables du groupe comme obsolètes
            for (int i = 0; i < this.pools[pool].Count; i++)
                this.pools[pool][i].UpToDate = false;
            // Puis les recalcule
            for (int i = 0; i < this.pools[pool].Count; i++)
                this.pools[pool][i].Compute();

            // Appelle l'événement OnBeforeFinished
            if (this.OnBeforeFinished != null)
                this.OnBeforeFinished(pool, this);

            // Appelle l'événement OnFinished
            if (this.OnFinished != null)
                this.OnFinished(pool, this);
        }

        private readonly PoolHash pools = new PoolHash();
    }
}
