using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EvoBoat.EvoAlg.BBO
{
    public abstract class BBOAlg<P, S, R, e> : EAlg<P, S, R, e>
        where P : IProblem<S, R>
        where S : VecSolution<R, e>, new()
        where R : IVector<e>, ICloneable<R>
    {
        public double MutationRate { get; set; }

        protected double[] immrs, emrs;
        public double[] ImmRates { get { return immrs; } }
        public double[] EmRates { get { return emrs; } }

        public BBOAlg() : base()
        {
            Name = "BBO";
        }

        public BBOAlg(P problem, int seed = 0) : base(problem, seed)
        {
            Name = "BBO";
        }

        public override void SetParameters()
        {
            Size = 50;
            MutationRate = 0.1;
        }

        public override void InitPop()
        {
            base.InitPop();
            immrs = new double[size];
            emrs = new double[size];
        }

        public override void Calculate()
        {
            double den = (worst.Fit - best.Fit + epsilon);
            for (int i = 0; i < pop.Length; i++)
            {
                immrs[i] = (pop[i].Fit - best.Fit + epsilon) / den;
                emrs[i] = (worst.Fit - pop[i].Fit + epsilon) / den;
            }
        }

        public virtual S Migrate(S sol, int index)
        {
            S sol1 = new S() { Content = sol.Content.Clone(), Fit = sol.Fit };
            bool bChanged = false;
            for (int d = 0, sel; d < Problem.Dimension; d++)
            {
                if (Rand.NextDouble() < immrs[index])
                {
                    sel = RouletteSelect(pop, index, emrs);
                    sol1.Content[d] = pop[sel].Content[d];
                    if (!bChanged) bChanged = true;
                }
            }
            if (bChanged)
                this.Evaluate(sol1);
            return sol1;
        }

        //public SingleSolutionOperator<S> Mutate;
        public abstract S Mutate(S sol, int index);

        public override void Evolve()
        {
            for (int i = 0; i < pop.Length; i++)
            {
                S sol = this.Migrate(pop[i], i);
                if (sol.Fit < pop[i].Fit)
                {
                    pop[i] = sol;
                    if (pop[i].Fit < best.Fit)
                        best = pop[i];
                }
                else if (!Object.ReferenceEquals(pop[i], best) && Rand.NextDouble() < MutationRate)
                {
                    this.Mutate(pop[i], i);
                    if (pop[i].Fit > worst.Fit)
                        worst = pop[i];
                }
            }
            iter++;
        }
    }
}
