using UnityEngine;

namespace NBC
{
    public class TimelineTaskCollection : TaskCollection
    {
        private float _startTime = -1;


        protected override NTaskStatus RunTasksAndCheckIfDone()
        {
            if (_startTime < 0) _startTime = Time.time;
            var st = NTaskStatus.Running;

            if (RawList.Count > 0)
            {
                for (var index = 0; index < RawList.Count; index++)
                {
                    var raw = RawList[index];
                    if (raw == null) continue;
                    var t = raw["time"];
                    if (t != null)
                    {
                        float time = 0;
                        if (t is int i)
                        {
                            time = i;
                        }
                        else if (t is float f)
                        {
                            time = f;
                        }
                        else if (t is string s)
                        {
                            float.TryParse(s, out time);
                        }

                        if (Time.time >= (_startTime + time))
                        {
                            CurrentTask.Add(RawList[index]);
                            RawList.RemoveAt(index);
                            index--;
                        }
                    }
                }
            }
            else if (RawList.Count <= 0 && CurrentTask.Count <= 0)
            {
                st = NTaskStatus.Success;
            }

            for (var index = 0; index < CurrentTask.Count; index++)
            {
                var element = CurrentTask[index];
                var childSt = element.Process();
                if (childSt >= NTaskStatus.Success)
                {
                    CurrentTask.RemoveAt(index);
                    index--;
                    FinishList.Add(element);
                }
            }

            return st;
        }

        public override void Reset()
        {
            base.Reset();
            _startTime = -1;
        }

        public override void Stop()
        {
            base.Stop();
            _startTime = -1;
        }

        public override void Clear()
        {
            base.Clear();
            _startTime = -1;
        }
    }
}