using System;
using System.Text.RegularExpressions;

namespace BehaviorTreeSlayer
{
    public class MagicRandom : CompositeNode
    {
        [OutField]
        public int[] Power;
        TreeNode last;
        public override TaskResult Tick(double dt, object args = null)
        {
            if (childs.Count == 0) return TaskResult.Fail;

            childs.Sort((a, b) => a.x < b.x ? -1 : 1);

            if (last == null)
            {
                Index = CheckRandom();
            }
            if (last != childs[Index])
            {
                childs[Index].Enter(args);
            }
            TreeNode curNode = childs[Index];
            TaskResult result = curNode.Tick(dt, args);
            last = curNode;
            curNode.state = result;
            if (result == TaskResult.Running)
            {
                return TaskResult.Running;
            }
            curNode.Exit(args);
            Index = CheckRandom();
            return result;
        }
        int CheckRandom()
        {
            int sum = 0;
            int length = Power.Length <= childs.Count ? Power.Length : childs.Count;
            for (int i = 0; i < length; i++)
            {
                sum += Power[i];
            }
            double r = new Random().NextDouble() * sum;
            int cache = 0;
            for (int i = 0; i < length; i++)
            {
                cache += Power[i];
                if (cache > r)
                {
                    return i;
                }
            }
            return length - 1;
        }
    }
}