using System.Collections.Generic;
using System.Linq;
using Cute;

namespace Wizard;

public class LoadQueue
{
	public delegate void Callback(string id);

	private class Data
	{
		public string ID { get; private set; }

		public List<string> PathList { get; set; }

		public Callback OnStart { get; set; }

		public Callback OnEnd { get; set; }

		public Data(string id, List<string> pathList, Callback onStart, Callback onEnd)
		{
			ID = id;
			PathList = pathList;
			OnStart = onStart;
			OnEnd = onEnd;
		}
	}

	private enum State
	{
		IDLE,
		LOAD
	}

	private readonly List<Data> _loadList = new List<Data>();

	private State _state;

	public bool IsChangingPauseLoad { get; private set; }

	public bool IsClearing { get; private set; }

	public bool IsEmpty
	{
		get
		{
			if (_loadList.Count <= 0)
			{
				return _state == State.IDLE;
			}
			return false;
		}
	}

	public void AddToFirst(string id, List<string> pathList, Callback onStart, Callback onEnd)
	{
		Add(isFirst: true, id, pathList, onStart, onEnd);
	}

	public void AddToLast(string id, List<string> pathList, Callback onStart, Callback onEnd)
	{
		Add(isFirst: false, id, pathList, onStart, onEnd);
	}

	public void Add(bool isFirst, string id, List<string> pathList, Callback onStart, Callback onEnd)
	{
		Remove(id);
		Data item = new Data(id, pathList, onStart, onEnd);
		if (isFirst)
		{
			_loadList.Insert(0, item);
		}
		else
		{
			_loadList.Add(item);
		}
	}

	public bool Remove(string id)
	{
		if (IsValidId(id))
		{
			return _loadList.RemoveAll((Data x) => x.ID == id) > 0;
		}
		return false;
	}

	public void StartLoad()
	{
		IsChangingPauseLoad = false;
		if (_state != State.LOAD)
		{
			_state = State.LOAD;
			LoadNext();
		}
	}

	private void LoadNext()
	{
		if (_loadList.Count <= 0)
		{
			_state = State.IDLE;
			return;
		}
		Data data = _loadList[0];
		_loadList.RemoveAt(0);
		data.OnStart?.Invoke(data.ID);
		if (data.PathList != null)
		{
			List<string> list = (data.PathList = data.PathList.Where((string path) => !string.IsNullOrEmpty(path)).ToList());
			List<string> list3 = list;
			if (list3.Count > 0)
			{
				Toolbox.ResourcesManager.StartCoroutine_LoadAssetGroupAsync(list3, delegate
				{
					EndOneLoad(data);
				});
				return;
			}
		}
		EndOneLoad(data);
	}

	private void EndOneLoad(Data data)
	{
		if (IsClearing)
		{
			_state = State.IDLE;
			IsClearing = false;
			if (data.PathList != null)
			{
				Toolbox.ResourcesManager.RemoveAssetGroup(data.PathList);
			}
		}
		else if (IsChangingPauseLoad)
		{
			_state = State.IDLE;
			IsChangingPauseLoad = false;
			data.OnEnd?.Invoke(data.ID);
		}
		else
		{
			data.OnEnd?.Invoke(data.ID);
			LoadNext();
		}
	}

	public void PauseLoad()
	{
		if (_state == State.LOAD)
		{
			IsChangingPauseLoad = true;
		}
	}

	public void Clear()
	{
		_loadList.Clear();
		if (_state == State.LOAD)
		{
			IsClearing = true;
		}
	}

	private static bool IsValidId(string id)
	{
		return !string.IsNullOrEmpty(id);
	}
}
