using System.IO;
using UnityEditor;
using UnityEngine;

namespace MajacloudSdk.Editor
{
    /// <summary>Exports the SDK folder (never the project's settings asset) as a .unitypackage.</summary>
    internal static class MajacloudPackageExporter
    {
        public static string DefaultFileName => "Majacloud-Unity-SDK-" + Majacloud.Version + ".unitypackage";

        public static void ExportInteractive()
        {
            var path = EditorUtility.SaveFilePanel("Export Majacloud SDK", Directory.GetParent(Application.dataPath)?.FullName ?? string.Empty, DefaultFileName, "unitypackage");
            if (string.IsNullOrEmpty(path)) return;
            Export(path);
            EditorUtility.RevealInFinder(path);
        }

        public static void Export(string outputPath)
        {
            var root = MajacloudEditorPaths.SdkRoot;
            if (root.StartsWith("Packages/")) throw new System.InvalidOperationException("Export from an Assets/ copy of the SDK, not from a package.");
            var directory = Path.GetDirectoryName(outputPath);
            if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) Directory.CreateDirectory(directory);
            AssetDatabase.ExportPackage(new[] { root }, outputPath, ExportPackageOptions.Recurse);
            Debug.Log("[Majacloud] Exported " + outputPath);
        }
    }
}
