﻿using System.IO;
using JLGames.RocketDriver.Actions.Utils;
using UnityEditor;

namespace JLGames.RocketDriver.Editor.Infra
{
    public static class EditorSelectionUtil
    {
        public class SelectionInfo
        {
            public readonly bool IsFile;
            public readonly FileSystemInfo Info;
            public readonly string AssetPath;

            public string AssetPathParent
            {
                get
                {
                    if (string.IsNullOrEmpty(AssetPath)) return null;
                    var index = AssetPath.LastIndexOf('/');
                    return AssetPath.Substring(0, index);
                }
            }

            public FileInfo FileInfo => Info as FileInfo;
            public DirectoryInfo DirectoryInfo => Info as DirectoryInfo;

            public SelectionInfo(bool isFile, string assetPath, FileSystemInfo info)
            {
                IsFile = isFile;
                AssetPath = assetPath;
                Info = info;
            }
        }

        /// <summary>
        /// Get the FileInfo information of the selected item in the current Project window
        /// 取得当前Project窗口中选中项的FileInfo信息
        /// </summary>
        /// <returns></returns>
        public static SelectionInfo GetSelectionFileInfo()
        {
            var guids = Selection.assetGUIDs;
            if (null == guids || guids.Length == 0) return null;
            var guid = guids[0];
            var assetPath = AssetDatabase.GUIDToAssetPath(guid);
            if (Directory.Exists(assetPath))
            {
                return new SelectionInfo(false, assetPath, new DirectoryInfo(assetPath));
            }

            if (File.Exists(assetPath))
            {
                return new SelectionInfo(true, assetPath, new FileInfo(assetPath));
            }

            return null;
        }
    }
}