using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine;
using UnityEngine.U2D;

namespace XGame.Editor.Asset.Tools
{
    internal class AssetReorderableList : IReorderableHandler, IDisposable
    {
        private FileType _fileType;
        private List<AssetInfoData> _assetInfoDatas;
        private KReorderableList _reorderableList;
        private bool _inited;
        public bool IsFoldout { set; get; }
        private double _totalMemorySize;
        private string _title;

        public AssetReorderableList(FileType fileType, List<AssetInfoData> assetInfoDatas)
        {
            _fileType = fileType;
            _assetInfoDatas = assetInfoDatas;
            //IsFoldout = fileType < FileType.Prefab;
            _title = $"{_fileType}  数量: {_assetInfoDatas.Count}";
        }

        public void OnGUI()
        {
            IsFoldout = EditorGUILayout.Foldout(IsFoldout, _title);
            if (IsFoldout)
            {
                Init();
                //开始水平布局
                EditorGUILayout.BeginHorizontal();
                //缩进14像素
                GUILayout.Space(14);
                //开始垂直布局
                EditorGUILayout.BeginVertical();
                if (_fileType == FileType.Atlas)
                {
                    EditorGUILayout.LabelField($"静态图集总共占用内存: {_totalMemorySize.ToString("F3")} M");
                }

                _reorderableList.DoLayoutList();
                //结束垂直布局
                EditorGUILayout.EndVertical();
                //结束水平布局
                EditorGUILayout.EndHorizontal();
            }
        }

        private void Init()
        {
            if (_inited) return;
            _inited = true;
            PackAtlases();
            _reorderableList = new KReorderableList(this);
        }
        private void PackAtlases()
        {
            if (_fileType == FileType.Atlas)
            {
                try
                {
                    var count = _assetInfoDatas.Count;
                    var spriteAtlasLst = new List<SpriteAtlas>();
                    var cacheDir = $"{Application.dataPath}/../Library/AtlasCache";
                    var storeInfo = typeof(SpriteAtlasExtensions).GetMethod("GetStoredHash", BindingFlags.Static | BindingFlags.NonPublic);
                    foreach (var data in _assetInfoDatas)
                    {
                        var assetPath = data.assetPath;
                        var sa = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(assetPath);
                        if (string.IsNullOrEmpty(assetPath) || sa == null)
                        {
                            Debug.LogError($"SpriteAtlas is null. Path:{assetPath} SpriteAtlas:{sa != null} ");
                        }
                        else
                        {
                            var storeHash = (Hash128)storeInfo.Invoke(null, new object[] { sa });
                            if (storeHash == default)
                            {
                                spriteAtlasLst.Add(sa);
                            }
                            else
                            {
                                var allFiles = System.IO.Directory.GetFiles(cacheDir, storeHash.ToString(), System.IO.SearchOption.AllDirectories);
                                if (allFiles.Length == 0)
                                {
                                    spriteAtlasLst.Add(sa);
                                }
                                else
                                {
                                    //Debug.Log($"SpriteAtlas Exists. Path:{assetPath} Hash:{storeHash} Data Count:{count}");
                                }
                            }
                        }
                    }
                    if (spriteAtlasLst.Count > 0)
                    {
                        SpriteAtlasUtility.PackAtlases(spriteAtlasLst.ToArray(), EditorUserBuildSettings.activeBuildTarget);
                    }
                    else
                    {
                        Debug.Log($"Don't need to packAtlases. AtlasAssetInfoData Count:{count}");
                    }
                }
                catch (Exception ex)
                {
                    Debug.LogException(ex);
                }
            }
        }
        #region IReorderableHandler 接口实现
        string IReorderableHandler.HeaderName => _title;

        string IReorderableHandler.HeaderTooltip => "图集资源需要先通过菜单: Build/CreateAtlas 创建图集后才能收集";

        int IReorderableHandler.DataCount => _assetInfoDatas.Count;

        IReorderableItem IReorderableHandler.CreateItem(bool isInit, int index)
        {
            if (index < _assetInfoDatas.Count)
            {
                if (_fileType == FileType.Atlas)
                {
                    var item = new AtlasAssetInfoItem(_assetInfoDatas[index] as AtlasAssetInfoData);
                    _totalMemorySize += item.TotalSize;
                    return item;
                }
                return new AssetInfoItem(_assetInfoDatas[index]);
            }
            throw new NotImplementedException();
        }
        void IReorderableHandler.RemoveItem(int index)
        {
            
        }
        void IReorderableHandler.ItemChangedIndex(int oldIndex, int newIndex)
        {
            var lastItem = _assetInfoDatas[oldIndex];
            var nextItem = _assetInfoDatas[newIndex];
            _assetInfoDatas[oldIndex] = nextItem;
            _assetInfoDatas[newIndex] = lastItem;
        }
        bool IReorderableHandler.IsCanAdd(int count, int index)
        {
            return false;
        }

        bool IReorderableHandler.IsCanRemove(int count, int index)
        {
            return false;
        }
        #endregion

        public void Dispose()
        {
            _assetInfoDatas.Clear();
            _assetInfoDatas = null;
            _reorderableList?.Dispose();
            _reorderableList = null;
            _inited = false;
        }
    }
}
