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

namespace EvoBoat.EvoAlg.IntDivision
{
    public class IntDiv_GA<P, S> : SGA<P, S, IntVector, int>
        where P : IntDivisionProblem<S>
        where S : VecSolution<IntVector, int>, new()
    {
        public static Func<EAlg<P, S, IntVector, int>, S, int, S> MutationFunc = (alg, sol, index) =>
        {
            int dmax = 0;
            for (int d = 1; d < sol.Content.Length; d++)
                if (sol.Content[d] > sol.Content[dmax])
                    dmax = d;
            int c = alg.Rand.Next(1, sol.Content[dmax]);
            sol.Content[dmax] -= c;
            sol.Content[alg.RandomSelectIndex(sol.Content.Length, dmax)] += c;
            alg.Evaluate(sol);
            return sol;
        };

        public IntDiv_GA() : base()
        { }

        public IntDiv_GA(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 Crossover(S sol1, S sol2)
        {
            int sum = 0, d = 0;
            int[] x = new int[Problem.Dimension];
            double a = Rand.NextDouble();
            for (d = 0; d < Problem.Dimension; d++)
            {
                x[d] = (int)Math.Round(a * sol1.Content[d] + (1 - a) * sol2.Content[d], 0);
                sum += x[d];
            }
            while (sum < Problem.Total)
            {
                d = Rand.Next(0, Problem.Dimension);
                x[d]++;
                sum++;
            }
            while (sum > Problem.Total)
            {
                d = Rand.Next(0, Problem.Dimension);
                if (x[d] > 0)
                {
                    x[d]--;
                    sum--;
                }
            }
            S ch = new S() { Content = x };
            Evaluate(ch);
            return ch;
        }

        public override S Mutate(S sol, int index)
        {
            return MutationFunc(this, sol, index);
        }
    }
}
