using System.IO;
using System.Collections.Generic;
using UnityEngine;

public static class ResourcePath
{
	private static Dictionary<string, Object> fallbackCache = new Dictionary<string, Object>();

	public static string Normalize(string path)
	{
		if (string.IsNullOrEmpty(path))
		{
			return path;
		}
		path = path.Replace('\\', '/').Trim();
		while (path.StartsWith("/"))
		{
			path = path.Substring(1);
		}
		string extension = Path.GetExtension(path);
		if (!string.IsNullOrEmpty(extension))
		{
			path = path.Substring(0, path.Length - extension.Length);
		}
		return path;
	}

	public static T Load<T>(string path) where T : Object
	{
		string normalizedPath = Normalize(path);
		T asset = Resources.Load<T>(normalizedPath);
		if (asset != null)
		{
			return asset;
		}
		asset = Resources.Load<T>(path);
		if (asset != null)
		{
			return asset;
		}
		return LoadByName<T>(normalizedPath);
	}

	public static TextAsset LoadText(string path)
	{
		TextAsset textAsset = Load<TextAsset>(path);
		if (textAsset != null)
		{
			return textAsset;
		}
		return Resources.Load<TextAsset>(Normalize(path) + ".bytes");
	}

	private static T LoadByName<T>(string normalizedPath) where T : Object
	{
		string name = Path.GetFileName(normalizedPath);
		if (string.IsNullOrEmpty(name))
		{
			return null;
		}
		string key = typeof(T).FullName + ":" + name.ToLowerInvariant();
		if (fallbackCache.TryGetValue(key, out Object cachedAsset))
		{
			return cachedAsset as T;
		}
		T[] assets = Resources.LoadAll<T>(string.Empty);
		for (int i = 0; i < assets.Length; i++)
		{
			if (assets[i] != null && string.Equals(assets[i].name, name, System.StringComparison.OrdinalIgnoreCase))
			{
				fallbackCache[key] = assets[i];
				return assets[i];
			}
		}
		fallbackCache[key] = null;
		return null;
	}
}
