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

namespace EvoBoat.EvoAlg.Perm
{
    public class Perm_BBOAlg<P, S> : BBOAlg<P, S, PermVector, int>
        where P : PermProblem<S>
        where S : VecSolution<PermVector, int>, new()
    {
        public Perm_BBOAlg() : base()
        { }

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

        public override void SetFactory()
        {
            if (Problem == null)
                throw new ArgumentNullException("Please assign the problem instance before set the factory");
            Factory = new PermSolutionFactory<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; d < Problem.Dimension; d++)
            {
                if (Rand.NextDouble() < immrs[index])
                {
                    sel = RouletteSelect(pop, index, emrs);
                    int d1 = sol1.Content.IndexOf(pop[sel].Content[d]);
                    if (d != d1 && !(d == 0 && d1 == pop[sel].Content.Length - 1) && !(d1 == 0 && d == pop[sel].Content.Length - 1))
                        sol1.Content.Swap(d, d1);
                    if (!bChanged) bChanged = true;
                }
            }
            if (bChanged) this.Evaluate(sol1);
            return sol1;
        }

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