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_LocalBBOAlg<P, S> : LocalBBOAlg<P, S, PermVector, int>
        where P : PermProblem<S>
        where S : VecSolution<PermVector, int>, new()
    {
        public Perm_LocalBBOAlg() : base()
        {
            this.FunSetToplogy = SetRandomTopology(Rand, 3);
        }

        public Perm_LocalBBOAlg(P problem, int seed = 0) : base(problem, seed)
        {
            this.FunSetToplogy = SetRandomTopology(Rand, 3);
            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)
        {
            S sol1 = new S() { Content = sol.Content.Clone(), Fit = sol.Fit };
            bool bChanged = false;
            int d = 0, n = Problem.Dimension, sel;
            while (d < n - 1)
            {
                if (Rand.NextDouble() < immrs[index])
                {
                    int len = Rand.Next(1, n - d);
                    sel = RouletteSelectNeighbor((s, i) => emrs[i], index);
                    int j = pop[sel].Content.IndexOf(sol1.Content[d]);
                    for (int c = 1; c < len; c++)
                    {
                        int k1 = sol1.Content.IndexOf(pop[sel].Content[(j + c) % n]);
                        if (d + c != k1)
                        {
                            sol1.Content.Swap(d + c, k1);
                            if (!bChanged) bChanged = true;
                        }
                    }
                    d += len;
                }
                else
                    d++;
            }
            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);
        }
    }
}
