using XGame.Editor.Asset.Tools;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace XGame.Editor.Build.AssetBundles
{
    public class ABPackerInfoItem : IReorderableItem, System.IDisposable, IReorderableItemData<ABPackerInfo>
    {
        public ABPackerInfo Data { get; private set; }
        public float Height { get; private set; }

        private readonly GUIContent assetContent = new GUIContent("Asset", "资源或者文件夹，只能选择Res/Addressable目录下的资源");
        private readonly GUIContent packerTypeContent = new GUIContent("Packer Type", "打包分类 \r\nTopDirectoryOnly：默认方式，当前目录的资源(不包含子目录)打一个包 \r\nAllDirectories：当前目录及子目录的资源打一个包 \r\nSingleAsset：单个资源打包");

        private Object _assetObj;

        public ABPackerInfoItem(ABPackerInfo data)
        {
            Data = data;
            _assetObj = AssetDatabase.LoadMainAssetAtPath(data.AssetPath);
        }

        void IReorderableItem.OnGUI(Rect rect)
        {
            var lastAsset = _assetObj;
            Height = 0;
            var lineH = EditorGUIUtility.singleLineHeight;
            var tempRect = rect;
            tempRect.x += 14;
            tempRect.width -= 14;
            tempRect.height = lineH;
            _assetObj = EditorGUI.ObjectField(tempRect, assetContent, _assetObj, typeof(Object), false);
            tempRect.y += lineH;
            Height += lineH;
            var assetPath = AssetDatabase.GetAssetPath(_assetObj);
            if (!string.IsNullOrEmpty(assetPath))
            {
                if (!AssetBundleUtils.IsValidPath(assetPath))
                //if (FileUtil.IsFileIgnore(assetPath) || !assetPath.StartsWith(FileUtil.ToRelativePath(PathDefine.Res/Addressable)))
                {
                    EditorUtility.DisplayDialog("资源选择错误", $"选择了错误的资源或文件夹，只能选择Res/Addressable目录下的资源. Path:{assetPath}", "确认");
                    _assetObj = lastAsset;
                    assetPath = AssetDatabase.GetAssetPath(_assetObj);
                }
            }
            Data.GUID = AssetDatabase.AssetPathToGUID(assetPath);
            var isFile = (!string.IsNullOrEmpty(assetPath) && File.Exists(assetPath));
            if (isFile)
            {
                Data.packerType = ABPackerType.SingleAsset;
                EditorGUI.BeginDisabledGroup(true);
            }
            Data.packerType = (ABPackerType)EditorGUI.EnumPopup(tempRect, packerTypeContent, Data.packerType);
            if (isFile)
            {
                EditorGUI.EndDisabledGroup();
            }
            tempRect.y += lineH;
            Height += lineH;
        }
        void System.IDisposable.Dispose()
        {
            Data = null;
            _assetObj = null;
        }
    }
}
