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

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

        public string Data { get; private set; }
        private Object _assetObj;

        public ABAssetItem(string assetGuid)
        {
            Data = assetGuid;
            var assetPath = AssetDatabase.GUIDToAssetPath(assetGuid);
            _assetObj = AssetDatabase.LoadMainAssetAtPath(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, _assetObj?.name ?? "", _assetObj, typeof(Object), false);
            tempRect.y += lineH;
            Height += lineH;
            var assetPath = AssetDatabase.GetAssetPath(_assetObj);
            if (!string.IsNullOrEmpty(assetPath))
            {
                if (!assetPath.StartsWith(PathDefine.ResAddressableRelative))
                //if (FileUtil.IsFileIgnore(assetPath) || !assetPath.StartsWith(FileUtil.ToRelativePath(PathDefine.ResAddressablePath)))
                {
                    EditorUtility.DisplayDialog("资源选择错误", $"选择了错误的资源或文件夹，只能选择Assets/Res/Addressable目录下的资源. Path:{assetPath}", "确认");
                    _assetObj = lastAsset;
                    assetPath = AssetDatabase.GetAssetPath(_assetObj);
                }
            }
            Data = AssetDatabase.AssetPathToGUID(assetPath);
        }

        void System.IDisposable.Dispose()
        {
            _assetObj = null;
        }
    }
}
