using System;
using System.IO;
using UnityEditor;

namespace XGame.Editor.Build.AssetBundles
{
    [Serializable]
    public class ABPackerInfo : IComparable
    {
        [UnityEngine.SerializeField]
        private long packerId;
        public ABPackerType packerType;
        public string GUID;

        public string AssetPath
        {
            get
            {
                if (string.IsNullOrEmpty(GUID))
                {
                    return string.Empty;
                }
                return AssetDatabase.GUIDToAssetPath(GUID);
            }
        }

        public bool IsDirectory => Directory.Exists(AssetPath);
        public bool IsFile => File.Exists(AssetPath);
        public long PackerId => packerId;
        public ABPackerInfo()
        {
            packerId = System.DateTime.Now.Ticks;
        }
        public override string ToString()
        {
            return $"PackerInfo GUID:{GUID} Type:{packerType} Path:{AssetPath}";
        }

        public int CompareTo(object obj)
        {
            var compare = obj as ABPackerInfo;
            if (compare == null) return -1;
            var result = packerType - compare.packerType;
            if (result == 0)
            {
                
                if (packerType == ABPackerType.SingleAsset)
                {
                    //资源在前，文件夹在后
                    int sign_0 = this.IsFile ? 0 : 1;
                    int sign_1 = compare.IsFile ? 0 : 1;
                    result = sign_0 - sign_1;
                    if (result == 0)
                    {
                        result = string.Compare(AssetPath, compare.AssetPath, StringComparison.OrdinalIgnoreCase);
                    }
                }
                else
                {
                    // 子文件夹在前，父文件夹在后
                    var path_0 = AssetPath;
                    var path_1 = compare.AssetPath;
                    if (path_0.Contains(path_1))
                    {
                        result = -1;
                    }
                    else if (path_1.Contains(path_0))
                    {
                        result = 1;
                    }
                    else
                    {
                        result = string.Compare(path_0, path_1, StringComparison.OrdinalIgnoreCase);
                    }
                }
            }
            return result;
        }
    }

}
