using XGame.Editor.Asset;
using XGame.Framework.Asset;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using XGame.Framework.i18n;

namespace XGame.Editor.Build.AssetBundles
{
    internal static class AssetBundleUtils
    {
        /// <summary>
        /// 检测一个资源路径是否有效
        /// 用于判断指定Asset是否可以打包AssetBundle
        /// </summary>
        /// <param name="assetPath">使用Unity的相对路径</param>
        /// <returns></returns>
        public static bool IsValidPath(string assetPath)
        {
            if (string.IsNullOrEmpty(assetPath))
            {
                return false;
            }
            //if (!File.Exists(assetPath))
            //{
            //    Debug.LogWarning($"File can't find. Path:{assetPath}");
            //    return false;
            //}
            //assetPath = FileUtil.ToRelativePath(assetPath);
            if (FileUtil.IsFileIgnore(assetPath))
            {
                return false;
            }
            if (assetPath.StartsWith(PathDefine.ResAddressableRelative))
            {
                //在Addressable资源目录下
                return true;
            }
            if (AddressableHelper.IsI18nAssetPath(assetPath))
            {
                //在国际化资源目录下
                return true;
            }
            return false;
        }
        /// <summary>
        /// 检查Assetbundle内是否存在同名资源
        /// </summary>
        /// <param name="assetBundleBuilds"></param>
        /// <returns></returns>
        public static bool CheckAssetsNameRepeat(Dictionary<long, AssetBundleData> assetBundleBuilds)
        {
            bool result = true;
            Dictionary<string, string> assetPathMap = new Dictionary<string, string>();
            foreach (var bundleBuild in assetBundleBuilds)
            {
                assetPathMap.Clear();
                foreach (var assetPath in bundleBuild.Value.assetNames)
                {
                    var fileName = Path.GetFileName(assetPath);
                    if (assetPathMap.ContainsKey(fileName))
                    {
                        result = false;
                        Debug.LogError($"AssetBundle存在重名资源。Bundle:{bundleBuild.Value.originBundleName} 重名资源1:{assetPathMap[fileName]} 重名资源2:{assetPath}");
                    }
                    else
                    {
                        assetPathMap.Add(fileName, assetPath);
                    }
                }
            }
            return result;
        }

        ///// <summary>
        ///// 返回ResStatic目录下资源的bundleName
        ///// 只有打了AssetBundle的资源才有效
        ///// </summary>
        ///// <param name="assetPath"></param>
        ///// <returns></returns>
        //public static string GetRawBundleName(string assetPath)
        //{
        //    var directoryRelative = FileUtil.ToRelativePath(Path.GetDirectoryName(assetPath)?.Replace("\\", "/"));
        //    string bundleName;
        //    var rawRelative = PathDefine.ResStaticRelative;
        //    if (directoryRelative.Equals(rawRelative))
        //    {
        //        bundleName = PathDefine.ResStaticName.ToLower();
        //    }
        //    else if (directoryRelative.Contains(rawRelative))
        //    {
        //        bundleName = directoryRelative.Replace(PathDefine.ResStaticRelative + "/", "").Replace("/", "_").ToLower();
        //    }
        //    else
        //    {
        //        Debug.LogError($"文件路径错误，该文件不在{rawRelative}");
        //        bundleName = string.Empty;
        //    }
        //    bundleName = $"{PathDefine.rawBundlePrefix}{bundleName}";
        //    return bundleName;
        //}

        /// <summary>
        /// 返回指定资源的bundleName，只对未设置Packer的资源有效
        /// </summary>
        /// <param name="assetPath"></param>
        /// <returns></returns>
        public static string GetBundleName(string assetPath)
        {
            //var assetPath = FileUtil.ToRelativePath(filePath);
            var directoryRelative = FileUtil.ToRelativePath(Path.GetDirectoryName(assetPath).Replace("\\", "/"));
            string bundleName;
            var languageType = AddressableHelper.GetLanguageTypeByAssetPath(assetPath);
            if (languageType != LanguageType.NONE)
            { //国际化资源
                if (directoryRelative.EndsWith(PathDefine.ResAddressableName))
                {
                    bundleName = $"{languageType}_{PathDefine.ResAddressableName}".ToLower();
                    bundleName = $"{LanguageUtils.ToName(languageType)}/{bundleName}";
                }
                else
                {
                    var offest = directoryRelative.IndexOf(PathDefine.ResAddressableName, StringComparison.Ordinal) + PathDefine.ResAddressableName.Length + 1;
                    bundleName = directoryRelative.Substring(offest).Replace("/", "_");
                    bundleName = $"{languageType}_{bundleName}".ToLower();
                    bundleName = $"{LanguageUtils.ToName(languageType)}/{bundleName}";
                }
            }
            else if (directoryRelative.Equals(PathDefine.ResAddressableRelative))
            {//主目录
                bundleName = PathDefine.ResAddressableName.ToLower();
            }
            else
            {
                bundleName = directoryRelative.Replace(PathDefine.ResAddressableRelative + "/", "").Replace("/", "_").ToLower();
            }
            return bundleName;
        }

        /// <summary>
        /// 加载 KCAssetBundleManifest.asset
        /// </summary>
        /// <returns></returns>
        public static AssetBundleInfosSo LoadManifest()
        {
            return UnityEditor.AssetDatabase.LoadAssetAtPath<AssetBundleInfosSo>(PathDefine.BundleManifestPath);
        }

    }
}
