using XGame.Editor.Asset.Tools;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace XGame.Editor.Build.AssetBundles
{
    public class ABGroupInfoItem : IReorderableItem, System.IDisposable, IReorderableItemData<ABGroupInfo>
    {
        private ABGroupInfo _data;
        public float Height { get; private set; }
        public ABGroupInfo Data
        {
            get
            {
                var assetGuids = _assetList.GetItemDatas();
                _data.guidList.Clear();
                foreach(var guid in assetGuids)
                {
                    if (!string.IsNullOrEmpty(guid) && !_data.guidList.Contains(guid))
                    {
                        _data.guidList.Add(guid);
                    }
                }
                return _data;
            }
        }

        private readonly GUIContent assetContent = new GUIContent("GroupName", "资源或者文件夹，只能选择Assets/Res/Addressable目录下的资源");

        private ABPackerReorderableList<ABAssetItem, string> _assetList;
        public ABGroupInfoItem(ABGroupInfo data)
        {
            if (data.guidList == null)
            {
                data.guidList = new List<string>();
            }
            _data = data;
            var toolTip = "资源或者文件夹，只能选择Assets/Res/Addressable目录下的资源";
            _assetList = new ABPackerReorderableList<ABAssetItem, string>(data.guidList, "资源列表", toolTip);
        }

        void IReorderableItem.OnGUI(Rect rect)
        {
            Height = 0;
            var lineH = EditorGUIUtility.singleLineHeight;
            var tempRect = rect;
            tempRect.x += 14;
            tempRect.width -= 14;
            tempRect.height = lineH;
            _data.groupName = EditorGUI.TextField(tempRect, assetContent, _data.groupName);
            tempRect.y += lineH;
            Height += lineH;
            _assetList.OnGUI(tempRect);
            var listHeight = _assetList.TotalHeight;
            tempRect.y += listHeight;
            Height += listHeight;
        }

        void System.IDisposable.Dispose()
        {
            (_assetList as System.IDisposable)?.Dispose();
            _assetList = null;
            _data = null;
        }


    }
}
