using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EvoBoat.EvoAlg;
using EvoBoat.EvoAlg.BBO;

namespace EvoBoat.EvoAlg.IntDivision
{
    public class IntDiv_BBOAlg<P, S> : BBOAlg<P, S, IntVector, int>
        where P : IntDivisionProblem<S>
        where S : VecSolution<IntVector, int>, new()
    {
        public IntDiv_BBOAlg() : base()
        { }

        public IntDiv_BBOAlg(P problem, int seed = 0) : base(problem, seed)
        {
            this.Factory = new IntDivisionSolutionFactory<P, S>(problem);
        }

        public override void SetFactory()
        {
            if (Problem == null)
                throw new ArgumentNullException("Please assign the problem instance before set the factory");
            this.Factory = new IntDivisionSolutionFactory<P, S>(Problem);
        }

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

        public override S Mutate(S sol, int index)
        {
            return IntDiv_GA<P, S>.MutationFunc(this, sol, index);
        }
    }
}
