using System.Linq;
using UnityEditor;
using UnityEngine;
using System.IO;
using System.Collections.Generic;
using UnityEngine.WSA;


[CustomEditor(typeof(Database))]
public class DatabaseEditor : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        if (GUILayout.Button("fetch assets"))
        {
            var targ = target as Database;

            targ.ScriptableObjects.Clear();
            targ.Prefabs.Clear();
            foreach (var folder in targ.Folders)
            {
                var path = AssetDatabase.GetAssetPath(folder);
                foreach (var file in GetAllPaths(path))
                {
                    var scriptableObject = AssetDatabase.LoadAssetAtPath<ScriptableObject>(file);
                    if (scriptableObject && !targ.ScriptableObjects.Contains(scriptableObject))
                    {
                        targ.ScriptableObjects.Add(scriptableObject);
                    }

                    var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(file);
                    if (prefab && !targ.Prefabs.Contains(prefab))
                    {
                        targ.Prefabs.Add(prefab);
                    }
                }
            }
            EditorUtility.SetDirty(target);
        }
    }

    private static string[] GetAllPaths(string target)
    {
        var files = Directory.GetFiles(target).ToList();
        foreach (var dir in Directory.GetDirectories(target))
        {
            files.AddRange(GetAllPaths(dir));
        }
        return files.ToArray();
    }
}
