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

namespace EvoBoat.EvoAlg.BBO
{
    public abstract class LocalBBOAlg<P, S, R, e> : BBOAlg<P, S, R, e>
        where P : IProblem<S, R>
        where S : VecSolution<R, e>, new()
        where R : IVector<e>, ICloneable<R>
    {
        public LocalBBOAlg() : base()
        {
            Name = "LocalBBO";
            FunSetToplogy = SetRandomTopology(Rand, 3);
        }

        public LocalBBOAlg(P problem, int seed = 0) : base(problem, seed)
        {
            Name = "LocalBBO";
            FunSetToplogy = SetRandomTopology(Rand, 3);
        }

        public override void InitPop()
        {
            linkMatrix = new bool[size, size];
            if (FunSetToplogy == null)
                throw new ArgumentNullException("SetToplogy function have not been set");
            linkMatrix = FunSetToplogy(linkMatrix);
            base.InitPop();
        }

        public override void Calculate()
        {
            base.Calculate();
            ComputeSumNeighborProbs((s, i) => emrs[i]);
        }

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