// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;

namespace WPFMA
{
    [InitializeOnLoad]
    internal static class WPFMAPackageImportQueue
    {
        private const string QueuePrefKey = "WPFMA.ImportQueue.Paths";
        private const string ProcessingPrefKey = "WPFMA.ImportQueue.Processing";

        static WPFMAPackageImportQueue()
        {
            AssetDatabase.importPackageCompleted += OnImportPackageCompleted;
            AssetDatabase.importPackageFailed += OnImportPackageFailed;
            AssetDatabase.importPackageCancelled += OnImportPackageCancelled;

            InitializeFromCommandLine();
        }

        public static IReadOnlyList<string> Items => LoadQueue();
        public static bool IsProcessing => EditorPrefs.GetBool(ProcessingPrefKey, false);

        private const string CommandLineReadKey = "WPFMA.ImportQueue.CommandLineRead";

        public static void InitializeFromCommandLine()
        {
            if (SessionState.GetBool(CommandLineReadKey, false))
            {
                StartIfNeeded();
                return;
            }
            SessionState.SetBool(CommandLineReadKey, true);

            var args = Environment.GetCommandLineArgs();
            var queuedPaths = new List<string>();

            foreach (var arg in args)
            {
                if (string.IsNullOrWhiteSpace(arg))
                    continue;

                if (!Path.GetExtension(arg).Equals(".unitypackage", StringComparison.OrdinalIgnoreCase))
                    continue;

                if (File.Exists(arg))
                    queuedPaths.Add(Path.GetFullPath(arg));
            }

            if (queuedPaths.Count > 0)
                EnqueueMany(queuedPaths);

            StartIfNeeded();
        }

        public static void Enqueue(string packagePath)
        {
            if (string.IsNullOrWhiteSpace(packagePath))
                return;

            var fullPath = Path.GetFullPath(packagePath);
            if (!File.Exists(fullPath) || !string.Equals(Path.GetExtension(fullPath), ".unitypackage", StringComparison.OrdinalIgnoreCase))
                return;

            var queue = LoadQueue().ToList();
            if (queue.Contains(fullPath, StringComparer.OrdinalIgnoreCase))
                return;

            queue.Add(fullPath);
            SaveQueue(queue);
            StartIfNeeded();
        }

        public static void EnqueueMany(IEnumerable<string> packagePaths)
        {
            if (packagePaths == null)
                return;

            foreach (var path in packagePaths)
                Enqueue(path);
        }

        public static void Clear()
        {
            SaveQueue(new List<string>());
            EditorPrefs.SetBool(ProcessingPrefKey, false);
        }

        public static void StartIfNeeded()
        {
            if (IsProcessing || LoadQueue().Count == 0)
                return;

            EditorApplication.delayCall += ProcessNext;
        }

        public static void ProcessNext()
        {
            var queue = LoadQueue();
            if (queue.Count == 0)
            {
                EditorPrefs.SetBool(ProcessingPrefKey, false);
                return;
            }

            if (IsProcessing)
                return;

            EditorPrefs.SetBool(ProcessingPrefKey, true);
            var nextPackage = queue[0];
            var remaining = queue.Skip(1).ToList();
            SaveQueue(remaining);
            // Checked for DLLs and token loggers first; if the user says no, carry on with the next one.
            WPFMASafety.ImportChecked(nextPackage, true, started =>
            {
                if (!started)
                    OnImportPackageCancelled(Path.GetFileNameWithoutExtension(nextPackage));
            });
        }

        private static void OnImportPackageCompleted(string packageName)
        {
            if (LoadQueue().Count > 0)
            {
                EditorApplication.delayCall += ProcessNext;
                return;
            }

            EditorPrefs.SetBool(ProcessingPrefKey, false);
        }

        private static void OnImportPackageFailed(string packageName, string errorMessage)
        {
            if (LoadQueue().Count > 0)
            {
                EditorApplication.delayCall += ProcessNext;
                return;
            }

            EditorPrefs.SetBool(ProcessingPrefKey, false);
        }

        private static void OnImportPackageCancelled(string packageName)
        {
            if (LoadQueue().Count > 0)
            {
                EditorApplication.delayCall += ProcessNext;
                return;
            }

            EditorPrefs.SetBool(ProcessingPrefKey, false);
        }

        public static string GetCurrentPackageName()
        {
            var queue = LoadQueue();
            return queue.Count == 0 ? "Idle" : Path.GetFileNameWithoutExtension(queue[0]);
        }

        private static List<string> LoadQueue()
        {
            var serialized = EditorPrefs.GetString(QueuePrefKey, string.Empty);
            if (string.IsNullOrWhiteSpace(serialized))
                return new List<string>();

            return serialized
                .Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries)
                .Where(path => !string.IsNullOrWhiteSpace(path))
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .ToList();
        }

        private static void SaveQueue(IEnumerable<string> queue)
        {
            var cleaned = queue
                .Where(path => !string.IsNullOrWhiteSpace(path))
                .Select(path => Path.GetFullPath(path))
                .Where(path => File.Exists(path))
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .ToList();

            EditorPrefs.SetString(QueuePrefKey, string.Join("|", cleaned));
        }
    }
}
#endif
