using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Sqlite3Plugin;
using UnityEngine;
using Wizard;

namespace Cute;

public class AssetManager : MonoBehaviour, IManager
{
	public enum _tag_datamode
	{
		DATAMODE_PREIN,
		DATAMODE_ALLDL,
		DATAMODE_HYBRID
	}

	private Dictionary<string, AssetHandle> handleDictionary = new Dictionary<string, AssetHandle>();

	private Dictionary<string, AssetBundleObject> objectDictionary = new Dictionary<string, AssetBundleObject>();

	private const int BACKGROUND_DOWNLOAD_BETWEEN_JOBS_WAIT_FRAMES = 5;

	private string[] categoryNameList;

	private static bool _isCryptAssetFileName = false;

	private AsyncJob _asyncJobDownload;

	private AsyncJob _asyncJobLoad;

	private bool _isCompressionAssetBundle = true;

	public bool _isUsePersistSound_PreIncircumstance;

	public const string assetbundleManifestName = "_assetmanifest";

	public const string manifestOfManifestName = "manifest_assetmanifest";

	public const string soundManifestName = "soundmanifest";

	public const string movieManifestName = "moviemanifest";

	public const string fontManifestName = "fontmanifest";

	public string currentMovieManifestName = "";

	private static string _savePath = null;

	private static string _packageDataPath = null;

	public bool _isUseStreamingAsset;

	private const string DIRECTORY_ASSET_BUNDLE = "a";

	public const string DIRECTORY_MOVIE = "m";

	public const string DIRECTORY_FONT = "f";

	public const string DIRECTORY_BGM = "b";

	public const string DIRECTORY_SE = "s";

	public const string DIRECTORY_VOICE = "v";

	public const string DIRECTORY_TEMPORARY = "t";

	public const string DIRECTORY_TEMPORARY_VOICE = "v/t";

	private const string DIRECTORY_MANIFEST = "manifest";

	private const string commonShaderAssetName = "card_shader_common.unity3d";

	private string manifestSavePath = "";

	private string bundleSavePath = "";

	private string soundSavePath = "";

	private string movieSavePath = "";

	private string fontSavePath = "";

	private string manifestPackagePath = "";

	private string bundlePackagePath = "";

	private string soundPackagePath = "";

	private string moviePackagePath = "";

	private string fontPackagePath = "";

	private int downloadReqCount;

	private int downloadCompCount;

	private int loadingReqCount;

	private int loadingCompCount;

	private int loadingManifestCompCount;

	public HashSet<string> predownloadCategories = new HashSet<string> { "common", "tutorial" };

	public HashSet<string> tutorialdownloadCategories = new HashSet<string> { "tutorial" };

	public List<string> NoUnloadAssetName = new List<string>();

	private static List<string> assetList = new List<string>();

	private static List<string> soundList = new List<string>();

	private static List<string> movieList = new List<string>();

	private float _normalResourceDownloadSize;

	private float _smallResourceDownloadSize;

	private float _downloadCompletedSize;

	private float _prevFrameEndTime;

	private List<string> _temporaryVoiceNameList = new List<string>();

	public string MovieManifesHeadtName = "moviemanifest";

	public string SoundManifesHeadtName = "soundmanifest";

	private bool _isLocalDatahashStoreRecoveryMode;

	private ManifestDatahashKVS _localDatahashStore;

	public static bool isCryptAssetFileName => _isCryptAssetFileName;

	public bool IsResourceDataBaseError { get; private set; }

	public bool IsBackgroundDownload { get; private set; }

	public bool isCompressionAssetBundle
	{
		get
		{
			return _isCompressionAssetBundle;
		}
		set
		{
			_isCompressionAssetBundle = value;
		}
	}

	public string manifestOfManifests { get; set; }

	public string manifestOfManifests_sub { get; set; }

	public bool IsDownloadJobIdle()
	{
		return _asyncJobDownload.IsIdle;
	}

	public void CancelDownloadAsyncJob()
	{
		_asyncJobDownload.Cancel();
	}

	public void SetDownloadAsBg(bool isBackground)
	{
		IsBackgroundDownload = isBackground;
		if (isBackground)
		{
			_asyncJobDownload.WantedWaitFramesBetweenJobs = 5;
		}
		else
		{
			_asyncJobDownload.WantedWaitFramesBetweenJobs = null;
		}
	}

	public void ClearManifestOfManifests()
	{
		manifestOfManifests = null;
		manifestOfManifests_sub = null;
	}

	private ManifestDatahashKVS GetLocalDatahashStore()
	{
		if (_localDatahashStore == null && !_isLocalDatahashStoreRecoveryMode)
		{
			string localDatahashStorePath = GetLocalDatahashStorePath();
			try
			{
				_localDatahashStore = new ManifestDatahashKVS(localDatahashStorePath);
			}
			catch (Exception ex)
			{
				HandleLocalDatahashException(ex);
			}
		}
		return _localDatahashStore;
	}

	public string GetLocalDatahashStorePath()
	{
		return GetAssetSaveRootPath() + "manifest.db";
	}

	private void HandleLocalDatahashException(Exception ex)
	{
		if (ex is DatabaseCorruptionException)
		{
			IsResourceDataBaseError = true;
			_isLocalDatahashStoreRecoveryMode = true;
			UnloadManifestHashDB();
			string localDatahashStorePath = GetLocalDatahashStorePath();
			if (File.Exists(localDatahashStorePath))
			{
				File.Delete(localDatahashStorePath);
			}
			UIManager instance = UIManager.GetInstance();
			if ((bool)instance)
			{
				instance.CreateConfirmationDialog(Data.SystemText.Get("System_0058")).OnClose = delegate
				{
					SoftwareReset.setAction();
					SoftwareReset.exec();
				};
			}
			else
			{
				SoftwareResetBase.SoftwareReset(null, null);
			}
			return;
		}
		throw ex;
	}

	public void SaveLocalDatahash(string name, string hash)
	{
		ManifestDatahashKVS localDatahashStore = GetLocalDatahashStore();
		if (localDatahashStore != null)
		{
			try
			{
				localDatahashStore.Set(name, hash);
			}
			catch (Exception ex)
			{
				HandleLocalDatahashException(ex);
			}
		}
	}

	public string GetLocalDatahash(string name)
	{
		ManifestDatahashKVS localDatahashStore = GetLocalDatahashStore();
		if (localDatahashStore != null)
		{
			try
			{
				return localDatahashStore.Get(name);
			}
			catch (Exception ex)
			{
				HandleLocalDatahashException(ex);
			}
		}
		return "";
	}

	public void DeleteLocalDatahashByPrefix(string prefix)
	{
		ManifestDatahashKVS localDatahashStore = GetLocalDatahashStore();
		if (localDatahashStore != null)
		{
			try
			{
				localDatahashStore.DeleteByPrefix(prefix);
			}
			catch (Exception ex)
			{
				HandleLocalDatahashException(ex);
			}
		}
	}

	public List<string> FindLocalDatahashByPattern(string patternEscaped)
	{
		List<string> result = null;
		ManifestDatahashKVS localDatahashStore = GetLocalDatahashStore();
		if (localDatahashStore != null)
		{
			try
			{
				result = localDatahashStore.FindLike(patternEscaped);
			}
			catch (Exception ex)
			{
				HandleLocalDatahashException(ex);
			}
		}
		return result;
	}

	public string EscapeLocalDatahashPattern(string patternNoEscaped)
	{
		string result = null;
		ManifestDatahashKVS localDatahashStore = GetLocalDatahashStore();
		if (localDatahashStore != null)
		{
			try
			{
				result = localDatahashStore.EscapeLikePattern(patternNoEscaped);
			}
			catch (Exception ex)
			{
				HandleLocalDatahashException(ex);
			}
		}
		return result;
	}

	public void UnloadManifestHashDB()
	{
		if (_localDatahashStore != null)
		{
			_localDatahashStore.Dispose();
			_localDatahashStore = null;
		}
	}

	public void DisableDatahashCache()
	{
		if (_localDatahashStore != null)
		{
			_localDatahashStore.DisableCache();
		}
	}

	public static string GetCryptFileName(string name)
	{
		return Cryptographer.ComputeSHA1(name);
	}

	public static string GetAssetSaveRootPath()
	{
		return _savePath;
	}

	public static string BuildAssetLocalCachePath(string directory, string filename)
	{
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.Append(GetAssetSaveRootPath());
		stringBuilder.Append(directory);
		stringBuilder.Append(isCryptAssetFileName ? GetCryptFileName(filename) : filename);
		return stringBuilder.ToString();
	}

	public static string BuildAssetLocalCachePath(string assetName)
	{
		string fileName = Path.GetFileName(assetName);
		return BuildAssetLocalCachePath(assetName.Substring(0, assetName.Length - fileName.Length), fileName);
	}

	public static bool AssetFileExists(string assetName)
	{
		return File.Exists(BuildAssetLocalCachePath(assetName));
	}

	private IEnumerator Start()
	{
		_isUseStreamingAsset = false;
		_savePath = Application.persistentDataPath + "/";
		_packageDataPath = Application.streamingAssetsPath + "/";
		while (Toolbox.ResourcesManager == null)
		{
			yield return 0;
		}
		int preferredParallelLoadNum = Toolbox.ResourcesManager.GetPreferredParallelLoadNum();
		int preferredParallelDownloadNum = Toolbox.ResourcesManager.GetPreferredParallelDownloadNum();
		preferredParallelLoadNum = ((preferredParallelLoadNum > preferredParallelDownloadNum) ? preferredParallelLoadNum : preferredParallelDownloadNum);
		_asyncJobDownload = new AsyncJob(this, preferredParallelLoadNum);
		_asyncJobDownload.Start();
		_asyncJobLoad = new AsyncJob(this, preferredParallelLoadNum);
		_asyncJobLoad.Start();
		Toolbox.AssetManager = this;
		yield return 0;
	}

	private void OnDestroy()
	{
		UnloadManifestHashDB();
	}

	public int GetManifestCount()
	{
		int num = categoryNameList.Length;
		int num2 = 1;
		int num3 = 1;
		int num4 = 1;
		return num + num2 + num3 + num4;
	}

	public bool CreateLocalFileCacheDirectories()
	{
		try
		{
			Directory.CreateDirectory(_savePath + "a");
			Directory.CreateDirectory(_savePath + "b");
			Directory.CreateDirectory(_savePath + "s");
			Directory.CreateDirectory(_savePath + "v");
			Directory.CreateDirectory(_savePath + "v/t");
			Directory.CreateDirectory(_savePath + "m");
			Directory.CreateDirectory(_savePath + "f");
			Directory.CreateDirectory(_savePath + "manifest");
		}
		catch (Exception)
		{
			return false;
		}
		return true;
	}

	private IEnumerator TryDownloadManifestOfManifest()
	{
		bool isError = false;
		ClearManifestOfManifests();
		if (CustomPreference.GetResourceLanguage() != CustomPreference.GetSoundMovieLanguage())
		{
			yield return StartCoroutine(DownloadManifestOfManifest("manifest_assetmanifest", delegate
			{
				isError = true;
			}, isSubMani: true));
		}
		if (isError)
		{
			yield break;
		}
		yield return StartCoroutine(DownloadManifestOfManifest("manifest_assetmanifest", delegate
		{
			isError = true;
		}, isSubMani: false));
		if (!isError)
		{
			bool isDone = false;
			CacheAsset("manifest_assetmanifest", delegate
			{
				isDone = true;
			});
			while (!isDone)
			{
				yield return 0;
			}
		}
	}

	private IEnumerator DownloadManifestOfManifest(string manifestOfManifestName, Action errorCallback, bool isSubMani)
	{
		bool isDone = false;
		AssetErrorState errorState = new AssetErrorState();
		RequestDownload(manifestOfManifestName, isManifest: true, new AssetRequestContext(delegate
		{
			isDone = true;
		}, null, errorState), isSubMani);
		while (!isDone)
		{
			yield return 0;
		}
		if (errorState.HasError())
		{
			errorCallback?.Invoke();
		}
	}

	private bool CheckExtraDownload()
	{
		return true;
	}

	private void DecideMovieManifestName()
	{
		currentMovieManifestName = string.Format("{0}_{1}", "moviemanifest", CustomPreference.GetSoundMovieLanguage().ToLower());
	}

	private void PrepareManifestList(out List<string> downloadList, out List<string> loadList, bool extraDownload)
	{
		List<string> list = new List<string>();
		loadList = new List<string>();
		for (int i = 0; i < categoryNameList.Length; i++)
		{
			string item = categoryNameList[i] + "_assetmanifest";
			list.Add(item);
			loadList.Add(item);
		}
		DecideMovieManifestName();
		if (extraDownload)
		{
			string[] array = new string[3] { "soundmanifest", currentMovieManifestName, "fontmanifest" };
			foreach (string item2 in array)
			{
				list.Add(item2);
				loadList.Add(item2);
			}
		}
		downloadList = new List<string>();
		foreach (string item3 in list)
		{
			if (handleDictionary.TryGetValue(item3, out var value))
			{
				if (value.isReDownloadAsset(CustomPreference.IsNormalResource))
				{
					downloadList.Add(item3);
				}
			}
			else
			{
				value = new AssetHandle(item3, null, null, null, null, null, isManifest: true);
				handleDictionary.Add(item3, value);
				downloadList.Add(item3);
			}
		}
	}

	public IEnumerator InitializeManifest(Action completeCallback, bool isTutorialDL)
	{
		QualitySettings.vSyncCount = 0;
		Application.targetFrameRate = 60;
		if (!CreateLocalFileCacheDirectories())
		{
			UIManager.GetInstance().isErrorProc = false;
			string titleLabel = Data.SystemText.Get("System_0020");
			DialogBase dialogBase = UIManager.GetInstance().CreateDialogClose(isSystem: true);
			if (dialogBase != null)
			{
				dialogBase.SetFadeButtonEnabled(flag: false);
				dialogBase.SetTitleLabel(titleLabel);
				dialogBase.SetText(Data.SystemText.Get("System_0021"));
				dialogBase.SetReturnMsg(UIManager.GetInstance().gameObject, "CommonResetGame");
				dialogBase.SetButtonLayout(DialogBase.ButtonLayout.GrayBtn);
				dialogBase.SetButtonText(Data.SystemText.Get("System_0006"));
				dialogBase.ClickSe_Btn1 = Se.TYPE.SYS_BTN_CANCEL_TRANS;
				dialogBase.SetPanelDepth(6000);
			}
			UIManager.GetInstance().isNoAvailMemory = true;
			UIManager.GetInstance().isRetryProc = false;
			while (!UIManager.GetInstance().isErrorProc)
			{
				yield return 0;
			}
			UIManager.GetInstance().isNoAvailMemory = false;
			if (!UIManager.GetInstance().isRetryProc)
			{
				SoftwareResetBase.SoftwareReset(null, null);
			}
		}
		LoadPreinManifest();
		yield return StartCoroutine(TryDownloadManifestOfManifest());
		bool extraDownload = CheckExtraDownload();
		PrepareManifestList(out var downloadList, out var loadList, extraDownload);
		if (downloadList.Count > 0)
		{
			yield return StartCoroutine(Toolbox.ResourcesManager.DownloadAssetGroup(downloadList, null, isProgress: false));
		}
		yield return StartCoroutine(Toolbox.ResourcesManager.LoadAssetGroupSync(loadList, null, isProgress: false));
		bool isDone = false;
		if (extraDownload)
		{
			isDone = false;
			RequestDownload("card_shader_common.unity3d", isManifest: false, delegate
			{
				isDone = true;
			});
			while (!isDone)
			{
				yield return 0;
			}
		}
		CacheAsset("card_shader_common.unity3d", delegate
		{
			isDone = true;
		});
		while (!isDone)
		{
			yield return 0;
		}
		loadList.Sort();
		ClearManifestOfManifests();
		Toolbox.SavedataManager.Save();
		QualitySettings.vSyncCount = 0;
		Application.targetFrameRate = Toolbox.QualityManager.GetFrameRate();
		completeCallback?.Invoke();
	}

	public bool IsShouldLoadPreinResource(string fileName)
	{
		return false;
	}

	public bool IsUseDownloadResource(string fileName)
	{
		return true;
	}

	private void LoadPreinManifest()
	{
	}

	private string CalcWholeResourceHash(List<string> loadedManfiestList)
	{
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.Append(Toolbox.SavedataManager.GetResourceVersion());
		stringBuilder.Append("|");
		int i = 0;
		for (int count = loadedManfiestList.Count; i < count; i++)
		{
			string text = loadedManfiestList[i];
			if (handleDictionary.TryGetValue(text, out var value))
			{
				if (string.IsNullOrEmpty(value.dataHash))
				{
					Debug.LogError("manifest hash not found: " + text);
					return "";
				}
				stringBuilder.Append(text);
				stringBuilder.Append(",");
				stringBuilder.Append(value.dataHash);
				stringBuilder.Append("|");
			}
		}
		SHA1CryptoServiceProvider sHA1CryptoServiceProvider = new SHA1CryptoServiceProvider();
		byte[] array = sHA1CryptoServiceProvider.ComputeHash(new UTF8Encoding().GetBytes(stringBuilder.ToString()));
		StringBuilder stringBuilder2 = new StringBuilder();
		for (int j = 0; j < array.Length; j++)
		{
			stringBuilder2.Append(Convert.ToString(array[j], 16).PadLeft(2, '0'));
		}
		sHA1CryptoServiceProvider.Clear();
		return stringBuilder2.ToString();
	}

	public void SetCategoryList(string[] _categoryList)
	{
		categoryNameList = _categoryList;
	}

	public string[] GetCategoryList()
	{
		return categoryNameList;
	}

	public bool RegistHandle(string key, AssetHandle handle)
	{
		try
		{
			handleDictionary.Add(key, handle);
			if (handle.directory.StartsWith("v/t", StringComparison.Ordinal))
			{
				_temporaryVoiceNameList.Add(Path.GetFileNameWithoutExtension(handle.filename));
			}
		}
		catch (Exception ex)
		{
			AssetHandle assetHandle = GetAssetHandle(key);
			if (assetHandle != null && assetHandle.isMultipleHandleIgnorAsset)
			{
				assetHandle.CopyWithCatchException(handle);
				assetHandle.reference--;
				return true;
			}
			Debug.LogError(ex.Message);
			return false;
		}
		return true;
	}

	public AssetBundleObject GetAssetBundleObject(string assetName)
	{
		AssetBundleObject value = null;
		if (objectDictionary.TryGetValue(assetName, out value))
		{
			return value;
		}
		return null;
	}

	public void DownloadAsset(string assetName, AssetRequestContext requestContext, bool isManifest = false)
	{
		RequestDownload(assetName, isManifest, requestContext);
	}

	public void SetAssetBundle(string filename, AssetBundle assetbundle, bool isMultipleHandleIgnorAsset = false)
	{
		if (objectDictionary.TryGetValue(filename, out var value))
		{
			if (!isMultipleHandleIgnorAsset)
			{
				for (int i = 0; i < value.objectArray.Count; i++)
				{
					UnityEngine.Object.DestroyImmediate(value.objectArray[i].baseObject, allowDestroyingAssets: true);
				}
			}
			value.objectArray.Clear();
			if (value.assetBundle != null)
			{
				value.assetBundle.Unload(unloadAllLoadedObjects: true);
			}
			value.assetBundle = assetbundle;
		}
		else
		{
			value = new AssetBundleObject();
			value.assetBundle = assetbundle;
			objectDictionary.Add(filename, value);
		}
	}

	public void SetObjectList(string filename, List<AssetObject> objectList)
	{
		if (objectDictionary.TryGetValue(filename, out var value))
		{
			value.objectArray = objectList;
		}
	}

	public bool HasObjectList(string filename)
	{
		return objectDictionary.ContainsKey(filename);
	}

	public void UnloadAssetBundle(string assetName)
	{
		if (objectDictionary.TryGetValue(assetName, out var value))
		{
			for (int i = 0; i < value.objectArray.Count; i++)
			{
				UnityEngine.Object.DestroyImmediate(value.objectArray[i].baseObject, allowDestroyingAssets: true);
			}
			value.objectArray.Clear();
			if (value.assetBundle != null)
			{
				value.assetBundle.Unload(unloadAllLoadedObjects: true);
				value.assetBundle = null;
			}
			objectDictionary.Remove(assetName);
		}
	}

	public void UnloadAssetAll()
	{
		foreach (KeyValuePair<string, AssetHandle> item in handleDictionary)
		{
			item.Value.Unload();
		}
	}

	public void UnloadAsset(string assetName)
	{
		if (!string.IsNullOrEmpty(assetName) && handleDictionary.TryGetValue(assetName, out var value) && value.assetType != AssetHandle.AssetType.Movie)
		{
			value.Unload();
		}
	}

	public void UnloadTemporaryAssetAll()
	{
		foreach (KeyValuePair<string, AssetHandle> item in handleDictionary)
		{
			if (item.Value.unloadTemporary)
			{
				item.Value.UnloadTemporary();
			}
		}
	}

	public void UnloadTemporaryAsset(string assetName)
	{
		if (handleDictionary.TryGetValue(assetName, out var value) && value.unloadTemporary)
		{
			value.UnloadTemporary();
		}
	}

	public void UnloadCommonAssetAll()
	{
		foreach (KeyValuePair<string, AssetHandle> item in handleDictionary)
		{
			if (item.Value.unloadCommon)
			{
				item.Value.UnloadCommon();
			}
		}
	}

	public void UnloadCommonAsset(string assetName)
	{
		if (handleDictionary.TryGetValue(assetName, out var value) && value.unloadCommon)
		{
			value.UnloadCommon();
		}
	}

	public void CacheAsset(string assetName, Action callback = null)
	{
		CacheAsset(assetName, new AssetRequestContext(delegate
		{
			if (callback != null)
			{
				callback();
			}
		}));
	}

	public void CacheAsset(string assetName, AssetRequestContext requestContext)
	{
		AssetHandle value = null;
		if (handleDictionary.TryGetValue(assetName, out value) && !value.useStreamingAsset)
		{
			value.Load(requestContext);
		}
		else if (requestContext != null && requestContext.callback != null)
		{
			requestContext.callback(value);
		}
	}

	public void CachePersistantAssetBeforeManifestLoad(string assetName, Action callback = null)
	{
		CachePersistantAssetBeforeManifestLoad(assetName, new AssetRequestContext(delegate
		{
			if (callback != null)
			{
				callback();
			}
		}));
	}

	public void CachePersistantAssetBeforeManifestLoad(string assetName, AssetRequestContext requestContext)
	{
		AssetHandle value = null;
		if (handleDictionary.TryGetValue(assetName, out value))
		{
			requestContext.callback(value);
			return;
		}
		value = new AssetHandle(assetName, "", null, null, null, null);
		if (File.Exists(value.BuildLocalCachePath()))
		{
			Toolbox.AssetManager.RegistHandle(assetName, value);
			value.Load(requestContext);
		}
		else if (requestContext != null && requestContext.callback != null)
		{
			requestContext.callback(value);
		}
	}

	public UnityEngine.Object LoadObject(string objectName, Type type, bool isIfFindLoad = false)
	{
		string value = objectName.ToLower() + ".";
		foreach (AssetBundleObject value2 in objectDictionary.Values)
		{
			int count = value2.objectArray.Count;
			for (int i = 0; i < count; i++)
			{
				AssetObject assetObject = value2.objectArray[i];
				if (assetObject.baseObject != null && (assetObject.baseObject.GetType() == type || assetObject.baseObject.GetType().IsSubclassOf(type)) && assetObject.basePath.IndexOf(value, StringComparison.Ordinal) != -1)
				{
					return assetObject.baseObject;
				}
			}
		}
		return null;
	}

	public UnityEngine.Object LoadObject(string assetName, string objectName, Type type)
	{
		string text = objectName.ToLower() + ".";
		if (objectDictionary.TryGetValue(assetName, out var value))
		{
			int count = value.objectArray.Count;
			for (int i = 0; i < count; i++)
			{
				if (value.objectArray[i].baseObject != null && text.Equals(value.objectArray[i].basePath) && (value.objectArray[i].baseObject.GetType() == type || value.objectArray[i].baseObject.GetType().IsSubclassOf(type)))
				{
					return value.objectArray[i].baseObject;
				}
			}
		}
		return null;
	}

	public object LoadObjectByte(string objectName, Type type, bool isIfFindLoad = false)
	{
		if (string.IsNullOrEmpty(objectName))
		{
			Debug.LogError("empty name for AssetManager.LoadObject");
			return null;
		}
		foreach (KeyValuePair<string, AssetBundleObject> item in objectDictionary)
		{
			AssetBundleObject value = item.Value;
			for (int i = 0; i < value.objectArray.Count; i++)
			{
				if (value.objectArray[i] != null && value.objectArray[i].baseObject != null && (type == typeof(UnityEngine.Object) || value.objectArray[i].baseObject.GetType() == type))
				{
					return value.objectArray[i].baseObject;
				}
			}
		}
		return null;
	}

	public void RegistCommonAsset(string assetName)
	{
		AssetHandle assetHandle = GetAssetHandle(assetName);
		if (assetHandle != null)
		{
			assetHandle.unloadCommon = true;
		}
	}

	public void RegistTemporaryAsset(string assetName)
	{
		AssetHandle assetHandle = GetAssetHandle(assetName);
		if (assetHandle != null)
		{
			assetHandle.unloadTemporary = true;
		}
	}

	public void AddDownloadJob(IEnumerator enumerator, Action cancelAction)
	{
		_asyncJobDownload.Add(enumerator, cancelAction);
	}

	public void AddLoadJob(IEnumerator enumerator, Action cancelAction)
	{
		_asyncJobLoad.Add(enumerator, cancelAction);
	}

	private void RequestDownload(string name, bool isManifest, Action callback, bool isSubMani = false)
	{
		RequestDownload(name, isManifest, new AssetRequestContext(delegate
		{
			if (callback != null)
			{
				callback();
			}
		}), isSubMani);
	}

	private void RequestDownload(string name, bool isManifest, AssetRequestContext requestContext, bool isSubMani = false)
	{
		if (isManifest && !handleDictionary.TryGetValue(name, out var value))
		{
			value = new AssetHandle(name, null, null, null, null, null, isManifest);
			handleDictionary.Add(name, value);
		}
		value = GetAssetHandle(name);
		if (value == null)
		{
			value = new AssetHandle(name, "", null, null, null, null);
			handleDictionary.Add(name, value);
		}
		value.isSubManifest = isSubMani;
		value.Download(requestContext);
	}

	public bool IsEnableAssetName(string assetName)
	{
		return handleDictionary.ContainsKey(assetName);
	}

	public AssetHandle GetAssetHandle(string assetName, bool isWarning = true)
	{
		AssetHandle value = null;
		handleDictionary.TryGetValue(assetName, out value);
		return value;
	}

	public void ClearAssetCacheAssetBundle()
	{
		foreach (KeyValuePair<string, AssetBundleObject> item in objectDictionary)
		{
			AssetBundleObject value = item.Value;
			List<AssetObject> objectArray = item.Value.objectArray;
			if (objectArray != null)
			{
				for (int i = 0; i < objectArray.Count; i++)
				{
					UnityEngine.Object.DestroyImmediate(objectArray[i].baseObject, allowDestroyingAssets: true);
				}
			}
			if (value.assetBundle != null)
			{
				value.assetBundle.Unload(unloadAllLoadedObjects: true);
			}
		}
		objectDictionary.Clear();
		handleDictionary.Clear();
	}

	public void ClearAllAssetFile()
	{
		ClearManifestAll();
		ClearAssetBundleAll(forceCleanCache: true);
		ClearSoundFileAll();
		ClearMovieAll();
		ClearFontAll();
		ClearTemporaryFileAll();
		Caching.ClearCache();
	}

	public void ClearManifestAll()
	{
		ClearManifestOfManifests();
		ClearLocalCache("manifest");
		if (_localDatahashStore != null)
		{
			_localDatahashStore.DeleteAll();
		}
	}

	public void ClearAssetBundleAll(bool forceCleanCache)
	{
		ClearLocalCache("a");
		if (forceCleanCache)
		{
			Caching.ClearCache();
		}
	}

	public void ClearMovieAll()
	{
		ClearLocalCache("m");
	}

	public void ClearFontAll()
	{
		ClearLocalCache("f");
	}

	public void ClearSoundFileAll()
	{
		ClearSoundFileBgm();
		ClearSoundFileSe();
		ClearSoundFileVoice();
	}

	public void ClearSoundFileBgm()
	{
		ClearLocalCache("b");
	}

	public void ClearSoundFileSe()
	{
		ClearLocalCache("s");
	}

	public void ClearSoundFileVoice()
	{
		ClearLocalCache("v");
	}

	public void ClearTemporaryFileAll()
	{
		ClearTemporaryVoiceFile();
	}

	public void ClearTemporaryVoiceFile()
	{
		ClearLocalCache("v/t");
	}

	private void ClearLocalCache(string keyword)
	{
		string value = keyword + "/";
		try
		{
			List<string> list = new List<string>();
			foreach (KeyValuePair<string, AssetHandle> item in handleDictionary)
			{
				if (item.Key.StartsWith(value))
				{
					list.Add(item.Key);
				}
			}
			int count = list.Count;
			for (int i = 0; i < count; i++)
			{
				handleDictionary.Remove(list[i]);
			}
			DeleteLocalDatahashByPrefix(keyword + "/");
			string path = _savePath + keyword;
			if (Directory.Exists(path))
			{
				Directory.Delete(path, recursive: true);
			}
		}
		catch (Exception ex)
		{
			Debug.LogError(ex.Message);
		}
	}

	public IEnumerator DownloadAssetBundleAll(Action callback)
	{
		assetList.Clear();
		foreach (KeyValuePair<string, AssetHandle> item in handleDictionary)
		{
			if (item.Value.IsAssetBundle())
			{
				assetList.Add(item.Key);
			}
		}
		yield return StartCoroutine(Toolbox.ResourcesManager.DownloadAssetGroup(assetList, callback));
	}

	public IEnumerator DownloadSoundAll(Action callback)
	{
		soundList.Clear();
		foreach (KeyValuePair<string, AssetHandle> item in handleDictionary)
		{
			if (item.Value.IsSound())
			{
				soundList.Add(item.Key);
			}
		}
		yield return StartCoroutine(Toolbox.ResourcesManager.DownloadAssetGroup(soundList, callback));
	}

	public IEnumerator DownloadMovieAll(Action callback)
	{
		movieList.Clear();
		foreach (KeyValuePair<string, AssetHandle> item in handleDictionary)
		{
			if (item.Value.IsMovie())
			{
				movieList.Add(item.Key);
			}
		}
		yield return StartCoroutine(Toolbox.ResourcesManager.DownloadAssetGroup(movieList, callback));
	}

	public IEnumerator PreDownloadListCoroutine(Action<List<string>, List<string>> onFinish)
	{
		Action<List<string>, List<string>, float, float> finish = delegate(List<string> normalResourceDownloadList, List<string> smallResourceDownloadList, float size, float smallResourceDownloadSize)
		{
			_normalResourceDownloadSize = size;
			_smallResourceDownloadSize = smallResourceDownloadSize;
			onFinish(normalResourceDownloadList, smallResourceDownloadList);
		};
		while (!Toolbox.ResourcesManager.CanStartDownload())
		{
			yield return new WaitForSeconds(1f);
		}
		PreDownloadListCoroutine(finish, withTutorial: true);
	}

	public void RefreshNeedDownloadFile()
	{
		Action<List<string>, List<string>, float, float> onFinish = delegate(List<string> normalResourceDownloadList, List<string> smallResourceDownloadList, float size, float smallResourceDownloadSize)
		{
			_normalResourceDownloadSize = size;
			_smallResourceDownloadSize = smallResourceDownloadSize;
		};
		PreDownloadListCoroutine(onFinish, withTutorial: true);
	}

	public void PreDownloadListCoroutine(Action<List<string>, List<string>, float, float> onFinish, bool withTutorial)
	{
		List<string> list = new List<string>();
		List<string> list2 = new List<string>();
		float num = 0f;
		float num2 = 0f;
		foreach (KeyValuePair<string, AssetHandle> item in handleDictionary)
		{
			AssetHandle value = item.Value;
			bool flag = withTutorial || !value.isTutorialDownload;
			if (!value.IsManifests() && value.isPreDownload && flag)
			{
				if (value.isReDownloadAsset(isNormalSizeResource: true))
				{
					list.Add(item.Key);
					num += value.manifestDataSize;
				}
				if (value.isReDownloadAsset(isNormalSizeResource: false))
				{
					list2.Add(item.Key);
					num2 += value.ManifestSmallDataSize;
				}
			}
		}
		onFinish.Call(list, list2, num, num2);
	}

	public float GetNeedDownloadSize(bool isNormalResource, bool isTutorial)
	{
		float num = 0f;
		foreach (KeyValuePair<string, AssetHandle> item in handleDictionary)
		{
			AssetHandle value = item.Value;
			if ((!isTutorial || value.isTutorialDownload) && value.isPreDownload && !value.IsManifests() && value.isReDownloadAsset(isNormalResource))
			{
				num += (isNormalResource ? value.manifestDataSize : value.ManifestSmallDataSize);
			}
		}
		return num;
	}

	public float GetTotalStrageUseSize(bool isNormalResource)
	{
		float num = 0f;
		foreach (KeyValuePair<string, AssetHandle> item in handleDictionary)
		{
			AssetHandle value = item.Value;
			if (value.isPreDownload && !value.IsManifests())
			{
				num += (isNormalResource ? value.manifestDataSize : value.ManifestSmallDataSize);
			}
		}
		return num;
	}

	public float GetDownloadSize(bool isNormalResource)
	{
		if (!isNormalResource)
		{
			return _smallResourceDownloadSize;
		}
		return _normalResourceDownloadSize;
	}

	public static string GetSuffixByDigit(float num)
	{
		int num2 = Mathf.FloorToInt(Mathf.Log(num, 2f)) + 1;
		if (num2 <= 0)
		{
			return (num * 1024f).ToString("0.0") + "KB";
		}
		if (num2 >= 11)
		{
			return (num / 1024f).ToString("0.0") + "GB";
		}
		return num.ToString("0.0") + "MB";
	}

	public List<string> GetTutorialDownloadList(bool isNormalResource)
	{
		List<string> list = new List<string>();
		if (isNormalResource)
		{
			_normalResourceDownloadSize = 0f;
		}
		else
		{
			_smallResourceDownloadSize = 0f;
		}
		foreach (KeyValuePair<string, AssetHandle> item in handleDictionary)
		{
			AssetHandle value = item.Value;
			if (value.IsManifests() || !value.isTutorialDownload)
			{
				continue;
			}
			if (isNormalResource)
			{
				if (value.isReDownloadAsset(isNormalSizeResource: true))
				{
					list.Add(item.Key);
					_normalResourceDownloadSize += value.manifestDataSize;
				}
			}
			else if (value.isReDownloadAsset(isNormalSizeResource: false))
			{
				list.Add(item.Key);
				_smallResourceDownloadSize += value.manifestDataSize;
			}
		}
		return list;
	}

	public int assetbundleOpenCount()
	{
		int num = 0;
		foreach (KeyValuePair<string, AssetBundleObject> item in objectDictionary)
		{
			if (item.Value.assetBundle != null)
			{
				num++;
			}
		}
		return num;
	}

	public int assetbundleListCount()
	{
		return objectDictionary.Count;
	}

	public IEnumerator InitializeSoundManifest()
	{
		handleDictionary.Remove("soundmanifest");
		bool isDone = false;
		RequestDownload("soundmanifest", isManifest: true, delegate
		{
			Directory.CreateDirectory(_savePath + "b");
			Directory.CreateDirectory(_savePath + "s");
			Directory.CreateDirectory(_savePath + "v");
			isDone = true;
		});
		while (!isDone)
		{
			yield return 0;
		}
	}

	public IEnumerator InitializeMovieManifest()
	{
		handleDictionary.Remove("moviemanifest");
		bool isDone = false;
		RequestDownload("moviemanifest", isManifest: true, delegate
		{
			Directory.CreateDirectory(_savePath + "m");
			isDone = true;
		});
		while (!isDone)
		{
			yield return 0;
		}
	}

	public void ResetDownloadCount()
	{
		downloadReqCount = 0;
		downloadCompCount = 0;
		_downloadCompletedSize = 0f;
		ResetLoadCount();
	}

	public void ResetLoadCount()
	{
		loadingReqCount = 0;
		loadingCompCount = 0;
		loadingManifestCompCount = 0;
	}

	public void createSavePath()
	{
		manifestSavePath = _savePath + "manifest/";
		bundleSavePath = _savePath + "a/";
		soundSavePath = _savePath;
		movieSavePath = _savePath;
		fontSavePath = _savePath;
	}

	public string getAssetSavePath(AssetHandle.AssetType _assetType)
	{
		switch (_assetType)
		{
		case AssetHandle.AssetType.Manifests:
			return manifestSavePath;
		case AssetHandle.AssetType.AssetBundle:
			return bundleSavePath;
		case AssetHandle.AssetType.Sound:
		case AssetHandle.AssetType.TemporarySound:
			return soundSavePath;
		case AssetHandle.AssetType.Movie:
			return movieSavePath;
		case AssetHandle.AssetType.Font:
			return fontSavePath;
		default:
			return bundleSavePath;
		}
	}

	public void createPackagePath()
	{
		manifestPackagePath = _packageDataPath + "manifest/";
		bundlePackagePath = _packageDataPath + "a/";
		soundPackagePath = _packageDataPath;
		moviePackagePath = _packageDataPath + CustomPreference.GetLanguageFolderName();
	}

	public string getAssetPackagePath(AssetHandle.AssetType _assetType)
	{
		switch (_assetType)
		{
		case AssetHandle.AssetType.Manifests:
			return manifestPackagePath;
		case AssetHandle.AssetType.AssetBundle:
			return bundlePackagePath;
		case AssetHandle.AssetType.Sound:
		case AssetHandle.AssetType.TemporarySound:
			return soundPackagePath;
		case AssetHandle.AssetType.Movie:
			return moviePackagePath;
		case AssetHandle.AssetType.Font:
			return fontPackagePath;
		default:
			return bundlePackagePath;
		}
	}

	public int GetDownloadMaxCount()
	{
		return downloadReqCount;
	}

	public int GetDownloadCurrentCount()
	{
		return downloadCompCount;
	}

	public float GetDownloadCompletedSize()
	{
		return _downloadCompletedSize;
	}

	public int GetLoadingMaxCount()
	{
		return loadingReqCount;
	}

	public int GetLoadingCurrentCount()
	{
		return loadingCompCount;
	}

	public int GetManifestMaxCount()
	{
		return categoryNameList.Length;
	}

	public int GetManifestCompleteCount()
	{
		return loadingManifestCompCount;
	}

	public void AddManifestCount()
	{
		loadingManifestCompCount++;
	}

	public void AddDownloadMaxCount(int cnt = -1)
	{
		if (cnt == -1)
		{
			downloadReqCount++;
		}
		else
		{
			downloadReqCount += cnt;
		}
	}

	public void AddDownloadCurrentCount()
	{
		downloadCompCount++;
	}

	public void AddDownloadCompletedSize(float size)
	{
		_downloadCompletedSize += size;
	}

	public void AddLoadingMaxCount(int cnt = -1)
	{
		if (cnt == -1)
		{
			loadingReqCount++;
		}
		else
		{
			loadingReqCount += cnt;
		}
	}

	public void AddLoadingCurrentCount(string strFileName)
	{
		loadingCompCount++;
	}

	public void AddNoUnloadAssetGroupName(string name)
	{
		if (name == "")
		{
			return;
		}
		for (int i = 0; i < NoUnloadAssetName.Count; i++)
		{
			if (NoUnloadAssetName[i].CompareTo(name) == 0)
			{
				return;
			}
		}
		NoUnloadAssetName.Add(name);
	}

	public void RemoveUnloadAssetGroupName(string name)
	{
		if (!(name == ""))
		{
			NoUnloadAssetName.Remove(name);
		}
	}

	public bool CheckSavedDataAccuracy(List<string> DataNameList)
	{
		if (DataNameList == null)
		{
			return true;
		}
		SHA1CryptoServiceProvider sHA1CryptoServiceProvider = new SHA1CryptoServiceProvider();
		int i = 0;
		for (int count = DataNameList.Count; i < count; i++)
		{
			string key = DataNameList[i];
			if (handleDictionary.TryGetValue(key, out var value))
			{
				string value2 = Utility.CreateHash(File.ReadAllBytes(value.BuildLocalCachePath())).ToString();
				if (!value.dataHash.Equals(value2))
				{
					sHA1CryptoServiceProvider.Clear();
					return false;
				}
			}
		}
		sHA1CryptoServiceProvider.Clear();
		return true;
	}

	public bool DeleteUnity3dAssetHash(List<string> deleteDataNameList)
	{
		int i = 0;
		for (int count = deleteDataNameList.Count; i < count; i++)
		{
			string key = deleteDataNameList[i];
			if (handleDictionary.TryGetValue(key, out var value))
			{
				Toolbox.SavedataManager.DeleteKey(value.directory + value.filename);
			}
		}
		return true;
	}

	public bool IsTemporaryVoice(string fileName)
	{
		return _temporaryVoiceNameList.Contains(fileName);
	}
}
