using System;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace BingoBrain.Editor
{
    public class AssetBundleBuildKit
    {
        public const string AssetBundleRootPath = "Assets/AssetHotFix/";
        public const string AssetBundleSuffix = ".assetbundle";
        static void SetABName(string assetPath)
        {
            var importerPath = $"Assets{assetPath[Application.dataPath.Length..]}";
            importerPath = importerPath.Replace("\\", "/");
            const string assetBundleRootPath = AssetBundleRootPath;

            if (importerPath.StartsWith(assetBundleRootPath))
            {
                var bundleName = importerPath.Replace(assetBundleRootPath, "");

                var endIndex = bundleName.LastIndexOf("/", StringComparison.Ordinal);

                if (endIndex <= 0)
                {
                    return;
                }

                var fileInfo = new FileInfo(importerPath);

                if ((fileInfo.Attributes & FileAttributes.Directory) == 0)
                {
                    try
                    {
                        bundleName = bundleName.ToLower().Substring(0, endIndex).Replace("/", ".");

                        var importer = AssetImporter.GetAtPath(importerPath);
                        if (importer != null)
                        {
                            importer.assetBundleName = $"{bundleName}{AssetBundleSuffix}";
                            if (importer.assetBundleName != null)
                            {
                                importer.assetBundleVariant = "";
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.LogError(importerPath);
                        Debug.LogError(endIndex);
                        Debug.LogError(e.Message);
                        throw;
                    }
                }
            }
        }


        public static void SetAssetBundlesName(string _assetsPath)
        {
            var dir = new DirectoryInfo(_assetsPath);

            var files = dir.GetFileSystemInfos();

            for (var i = 0; i < files.Length; i++)
            {
                if (files[i] is DirectoryInfo)
                {
                    SetAssetBundlesName(files[i].FullName);
                }
                else if (!files[i].Name.EndsWith(".meta"))
                {
                    SetABName(files[i].FullName);
                }
            }
        }


        public static void ClearAssetBundlesName()
        {
            var abNames = AssetDatabase.GetAllAssetBundleNames();


            for (var i = 0; i < abNames.Length; i++)
            {
                AssetDatabase.RemoveAssetBundleName(abNames[i], true);
            }
        }
    }
}