using System.IO;
using Cute;
using UnityEngine;

namespace Wizard;

public class SpecialTitleAssetBundle : MonoBehaviour
{
	private AssetHandle _handle;

	private string _id;

	public GameObject _specialTitle;

	public bool IsSetupFinish { get; private set; }

	private static string GetSpecialTitlePath(string id, bool isFetch)
	{
		return Toolbox.ResourcesManager.GetAssetTypePath(id, ResourcesManager.AssetLoadPathType.SpecialTitle, isFetch);
	}

	private static string GetBGMCueName(string id)
	{
		return "bgm_title_" + id;
	}

	private static bool IsBGMAvailable(string id)
	{
		return File.Exists(Path.Combine(Application.persistentDataPath, "b", GetBGMCueName(id) + ".awb"));
	}

	public static bool IsAvailableTitleAssetBundle(string id)
	{
		if (!IsBGMAvailable(id))
		{
			return false;
		}
		return File.Exists(new AssetHandle(GetSpecialTitlePath(id, isFetch: false), null, null, null, null, null).BuildLocalCachePath());
	}

	public void Initialize(string id)
	{
		if (!IsAvailableTitleAssetBundle(id))
		{
			return;
		}
		_id = id;
		_handle = new AssetHandle(GetSpecialTitlePath(id, isFetch: false), null, null, null, null, null);
		_handle.Load(delegate
		{
			_specialTitle = NGUITools.AddChild(base.gameObject, Toolbox.ResourcesManager.LoadObject(GetSpecialTitlePath(id, isFetch: true)) as GameObject);
			ChangeableTitleUIParts component = _specialTitle.gameObject.GetComponent<ChangeableTitleUIParts>();
			if (component != null)
			{
				component.Init();
			}
			IsSetupFinish = true;
		});
	}

	public void PlayBGM()
	{
		GameMgr.GetIns().GetSoundMgr().PlayBGM(GetBGMCueName(_id), 0f, 0L);
	}

	public void UnloadBGM()
	{
		Toolbox.AudioManager.RemoveCueSheet(GetBGMCueName(_id));
		GameMgr.GetIns().GetSoundMgr().UnloadBGM(GetBGMCueName(_id));
	}

	public void RemoveSpecialTitle()
	{
		if (_specialTitle != null)
		{
			Object.Destroy(_specialTitle);
			_specialTitle = null;
		}
	}

	private void OnDestroy()
	{
		if (_handle != null)
		{
			_handle.Unload();
		}
	}
}
