using System;
using TMPro;
using UnityEditor;
using UnityEngine;

namespace MajacloudSdk.Editor
{
    /// <summary>Makes sure TextMeshPro's essential resources (default font) are imported before building UI.</summary>
    internal static class TmpResources
    {
        public static bool IsReady => Resources.Load<TMP_Settings>("TMP Settings") != null;

        /// <summary>Runs <paramref name="onReady"/> once the resources exist, importing them first in the editor UI.</summary>
        public static void Ensure(Action onReady)
        {
            if (IsReady)
            {
                onReady?.Invoke();
                return;
            }
            if (Application.isBatchMode)
            {
                // Package imports finish on a later editor update, which a -quit batch run never reaches.
                throw new InvalidOperationException("TextMesh Pro essential resources are not imported. Run MajacloudSdk.Editor.MajacloudBatch.EnsureTmpResources (without -quit) first.");
            }
            Import(_ => onReady?.Invoke());
        }

        /// <summary>Imports the essential resources package; <paramref name="done"/> receives whether they are usable afterwards.</summary>
        public static void Import(Action<bool> done)
        {
            Debug.Log("[Majacloud] Importing TextMeshPro essential resources…");
            AssetDatabase.ImportPackageCallback completed = null;
            AssetDatabase.ImportPackageFailedCallback failed = null;
            completed = _ =>
            {
                Unsubscribe();
                AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
                done?.Invoke(IsReady);
            };
            failed = (_, error) =>
            {
                Unsubscribe();
                Debug.LogWarning("[Majacloud] TMP resources import failed: " + error);
                done?.Invoke(false);
            };
            void Unsubscribe()
            {
                AssetDatabase.importPackageCompleted -= completed;
                AssetDatabase.importPackageFailed -= failed;
            }
            AssetDatabase.importPackageCompleted += completed;
            AssetDatabase.importPackageFailed += failed;
            TMP_PackageResourceImporter.ImportResources(true, false, false);
        }

        public static TMP_FontAsset DefaultFont()
        {
            // TMP_Settings.defaultFontAsset throws when the settings asset is missing, so check it first.
            return Resources.Load<TMP_Settings>("TMP Settings") != null ? TMP_Settings.defaultFontAsset : null;
        }
    }
}
