using System;
using System.Collections.Generic;

namespace ChillConnect
{
    public class TaskSequence
    {
        public Action onFinish;
        private List<TaskProcedure> taskList;
        private bool isCancel = false;

        public int Count => taskList.Count;

        public TaskSequence Add(Action<TaskProcedure> taskFunc)
        {
            TaskProcedure task = new TaskProcedure();
            task.taskSequence = this;
            task.onTaskFunc = taskFunc;
            taskList.Add(task);
            return this;
        }

        public TaskSequence Add(bool result, Action<TaskProcedure> trueTaskFunc)
        {
            if (!result) return this;
            return Add(trueTaskFunc);
        }

        public TaskSequence Run()
        {
            if (isCancel)
                return null;
            for (int i = 0; i < taskList.Count - 1; i++)
            {
                int index = i;
                int nextIndex = index + 1;
                taskList[index].onComplete = () => taskList[nextIndex].onTaskFunc(taskList[nextIndex]);
            }

            if (taskList.Count > 0)
            {
                taskList[taskList.Count - 1].onComplete = onFinish;
                taskList[0].onTaskFunc(taskList[0]);
            }

            return this;
        }

        public TaskSequence Clear()
        {
            onFinish = null;
            if (taskList != null)
            {
                foreach (TaskProcedure task in taskList)
                {
                    task?.Dispose();
                }

                taskList.Clear();
            }
            else
            {
                taskList = new List<TaskProcedure>();
            }

            return this;
        }
    }

    public class TaskProcedure
    {
        public TaskSequence taskSequence;
        public Action<TaskProcedure> onTaskFunc;
        public Action onComplete;

        public void InvokeComplete()
        {
            if (onComplete != null)
            {
                onComplete();
            }
        }

        public void Dispose()
        {
            taskSequence = null;
            onTaskFunc = null;
            onComplete = null;
        }
    }
}