using System.Collections;
using System.Collections.Generic;
using Cute;
using UnityEngine;

namespace Wizard;

public class ScenarioSummary
{
	public class Data
	{
		public string Title { get; }

		public string PastSummary { get; }

		public string BeforeSummary { get; }

		public string AfterSummary { get; }

		public Data()
		{
		}

		public Data(string title, string pastSummary, string beforeSummary, string afterSummary)
		{
			Title = title;
			PastSummary = pastSummary;
			BeforeSummary = beforeSummary;
			AfterSummary = afterSummary;
		}
	}

	private const string FILE_NAME_PREFIX = "scenario_text_summary_";

	private static readonly int CLASS_NONE;

	private Dictionary<string, Data> _dataTable = new Dictionary<string, Data>();

	private string _loadedAsset;

	public bool IsValid { get; private set; }

	public ScenarioSummary(int sectionId, int? sectionClassId)
	{
		ScenarioSummary scenarioSummary = this;
		IsValid = false;
		int processedClassId = (sectionClassId.HasValue ? sectionClassId.Value : CLASS_NONE);
		ResourcesManager resMgr = Toolbox.ResourcesManager;
		string fileName = "scenario_text_summary_" + sectionId;
		_loadedAsset = resMgr.GetAssetTypePath(fileName, ResourcesManager.AssetLoadPathType.StoryText);
		resMgr.StartCoroutine_LoadAssetGroupAsync(_loadedAsset, delegate
		{
			foreach (ArrayList item in Utility.ConvertCSV((resMgr.LoadObject(resMgr.GetAssetTypePath(fileName, ResourcesManager.AssetLoadPathType.StoryText, isfetch: true)) as TextAsset).ToString()))
			{
				string[] array = (string[])item.ToArray(typeof(string));
				int num = -1;
				if (int.Parse(array[++num]) == processedClassId)
				{
					string chapterId = array[++num];
					string text = array[++num];
					int? subChapterId = (string.IsNullOrEmpty(text) ? ((int?)null) : new int?(int.Parse(text)));
					string key = CreateKey(chapterId, subChapterId);
					Data value = new Data(array[++num], array[++num], array[++num], array[++num]);
					scenarioSummary._dataTable.Add(key, value);
				}
			}
			scenarioSummary.IsValid = true;
		});
	}

	public void Dispose()
	{
		Toolbox.ResourcesManager.RemoveAsset(_loadedAsset);
		_loadedAsset = null;
		_dataTable.Clear();
	}

	public Data GetData(string chapterId, int? subChapterId = null)
	{
		string key = CreateKey(chapterId, subChapterId);
		if (_dataTable.TryGetValue(key, out var value))
		{
			return value;
		}
		Debug.LogError("チャプター 「" + chapterId + "」 の ScenarioSummary のデータが見つかりませんでした。");
		return new Data();
	}

	private static string CreateKey(string chapterId, int? subChapterId)
	{
		if (!subChapterId.HasValue || subChapterId == StoryChapterData.SUB_CHAPTER_ALL)
		{
			return chapterId;
		}
		return $"{chapterId}_{subChapterId}";
	}
}
