using System.Collections.Generic;
using System.Linq;
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;
using UnityEditor;
using UnityEngine;

namespace VOID.Editor.EditorWindow
{
    public class ForceReserializeAssets : OdinEditorWindow
    {
        [MenuItem("VOID RPG/Assets/Force Reserialize Assets", priority = 1)]
        private static void OpenWindow() => GetWindow<ForceReserializeAssets>().Show();
        
        [InfoBox(
            "<b>WHY use this:</b>\n" +
            "- Update all names of properties when changed by <b>FormerlySerializedAs</b>\n" +
            "\n" +
            "<b>HOW use this:</b>\n" +
            "- Add all files to update serialized data and press <b>Reserialize</b>\n" +
            "- OR! Just press <b>Serialize Everything</b>, but it will go through all files in project"
            )]
        [ShowInInspector, AssetsOnly] private List<Object> _files = new(); 
        
        [Button(ButtonSizes.Gigantic)]
        public void Reserialize()
        {
            var paths = _files
                .Select(AssetDatabase.GetAssetPath)
                .SelectMany(file => AssetDatabase.IsValidFolder(file) ? GetAssetsPathsFromFolder(file) : new[] { file })
                .Distinct()
                .ToList();
            
            AssetDatabase.ForceReserializeAssets(paths);
                
            _files.Clear();
        }
        
        [Button(Name = "Reserialize Everything")]
        [GUIColor(1, 0, 0)]
        public void ReserializeEverything()
        {
            if (EditorUtility.DisplayDialog(
                    "Reserialize Everything",
                    "Are you sure? It'll be very long process, around ~30 minutes!",
                    "Yes, do it",
                    "No"))
            {
                AssetDatabase.ForceReserializeAssets();
            }
        }

        private string[] GetAssetsPathsFromFolder(string folderPath)
        {
            return AssetDatabase.FindAssets("", new[] { folderPath }).Select(AssetDatabase.GUIDToAssetPath).ToArray();
        }
    }
}