﻿using System;
using System.Collections.Generic;
using JLGames.RocketDriver.Actions.Utils;
using JLGames.RocketDriver.CSharp.Utils;
using UnityEditor;
using UnityEngine;
using FileUtil = JLGames.RocketDriver.CSharp.Utils.FileUtil;

namespace JLGames.RocketDriver.Editor.Infra
{
    public static class EditorAssetUtil
    {
        /// <summary>
        /// Get all file paths in the project
        /// 取项目中全部文件路径
        /// </summary>
        /// <returns></returns>
        public static List<string> GetFilePaths()
        {
            return GetAssetPaths(path =>
            {
                var absPath = UnityPathUtil.CombineUnityPath(Application.dataPath, path);
                return FileUtil.Exists(absPath);
            });
        }

        /// <summary>
        /// Get all directory paths in the project
        /// 取项目中全部目录路径
        /// </summary>
        /// <returns></returns>
        public static List<string> GetFolderPaths()
        {
            return GetAssetPaths(path =>
            {
                var absPath = UnityPathUtil.CombineUnityPath(Application.dataPath, path);
                return DirectoryUtil.Exists(absPath);
            });
        }

        /// <summary>
        /// Get the paths that meets the conditions
        /// 取符合条件的资源路径
        /// </summary>
        /// <param name="match"></param>
        /// <returns></returns>
        public static List<string> GetAssetPaths(Predicate<string> match)
        {
            var paths = AssetDatabase.GetAllAssetPaths();
            var rs = new List<string>();
            foreach (var path in paths)
            {
                if (!match.Invoke(path)) continue;
                rs.Add(path);
            }

            rs.Sort();
            return rs;
        }

        /// <summary>
        /// Find image assets by name
        /// 通过名称查找图片资产
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static Texture2D GetTextureFromName(string name)
        {
            var found = AssetDatabase.FindAssets(name);
            if (found.Length > 0)
                return AssetDatabase.LoadAssetAtPath<Texture2D>(AssetDatabase.GUIDToAssetPath(found[0]));

            return Texture2D.whiteTexture;
        }
    }
}