// 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;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace WPFMA
{
    internal static class WPFMAPackageBuilder
    {
        private const string StagingRoot = "Assets/WPFMA-SDK/Packages";

        internal sealed class Plan
        {
            public GameObject Avatar;
            public string PrefabPath;
            public string Problem;

            public readonly List<string> AssetPaths = new List<string>();
            public readonly List<string> PackageRequirements = new List<string>();
            public readonly List<KeyValuePair<string, int>> Breakdown = new List<KeyValuePair<string, int>>();

            public long Bytes;
            public bool Usable => Problem == null && PrefabPath != null;
        }

        internal static Plan Scan(GameObject avatar)
        {
            var plan = new Plan { Avatar = avatar };
            if (avatar == null)
            {
                plan.Problem = "Pick an avatar prefab, or select one in the scene.";
                return plan;
            }

            plan.PrefabPath = ResolvePrefabPath(avatar);
            if (plan.PrefabPath == null)
            {
                plan.Problem = "That object is not a prefab. Drag it into the Project window first, then pick the prefab.";
                return plan;
            }

            var dependencies = AssetDatabase.GetDependencies(new[] { plan.PrefabPath }, true);
            var byType = new Dictionary<string, int>();
            var requirements = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);

            foreach (var path in dependencies)
            {
                if (path.StartsWith("Packages/", StringComparison.OrdinalIgnoreCase))
                {
                    string requirement = PackageOf(path);
                    if (requirement != null)
                        requirements.Add(requirement);
                    continue;
                }

                if (!path.StartsWith("Assets/", StringComparison.OrdinalIgnoreCase))
                    continue;

                plan.AssetPaths.Add(path);

                var info = new FileInfo(path);
                if (info.Exists)
                    plan.Bytes += info.Length;

                string label = LabelFor(path);
                int count;
                byType.TryGetValue(label, out count);
                byType[label] = count + 1;
            }

            plan.PackageRequirements.AddRange(requirements);
            plan.Breakdown.AddRange(byType.OrderByDescending(pair => pair.Value));
            return plan;
        }

        internal static bool Build(Plan plan, bool includeScene, out string message)
        {
            message = null;
            if (plan == null || !plan.Usable)
            {
                message = plan?.Problem ?? "Nothing to package.";
                return false;
            }

            string name = Path.GetFileNameWithoutExtension(plan.PrefabPath);
            string destination = EditorUtility.SaveFilePanel("Save the avatar package",
                Environment.GetFolderPath(Environment.SpecialFolder.Desktop), name, "unitypackage");
            if (string.IsNullOrEmpty(destination))
                return false;

            var paths = new List<string>(plan.AssetPaths);
            string scenePath = null;

            try
            {
                if (includeScene)
                {
                    scenePath = WriteScene(plan.PrefabPath, name);
                    if (scenePath != null)
                        paths.Add(scenePath);
                }

                string notesPath = WriteNotes(plan, name, scenePath);
                if (notesPath != null)
                    paths.Add(notesPath);

                AssetDatabase.ExportPackage(paths.Distinct().ToArray(), destination, ExportPackageOptions.Default);
            }
            catch (Exception e)
            {
                message = "Could not build the package: " + e.Message;
                return false;
            }

            EditorUtility.RevealInFinder(destination);
            message = "Packed " + paths.Count + " asset(s) into " + Path.GetFileName(destination) +
                      (plan.PackageRequirements.Count > 0
                          ? ". " + plan.PackageRequirements.Count + " package(s) must be installed separately."
                          : ".");
            return true;
        }

        private static string WriteScene(string prefabPath, string name)
        {
            var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
            if (prefab == null)
                return null;

            string folder = StagingRoot + "/" + Sanitize(name);
            Directory.CreateDirectory(folder);
            string scenePath = folder + "/" + Sanitize(name) + ".unity";

            var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive);
            try
            {
                var instance = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
                if (instance != null)
                {
                    instance.name = prefab.name;
                    SceneManager.MoveGameObjectToScene(instance, scene);
                }

                var light = new GameObject("Directional Light", typeof(Light));
                light.GetComponent<Light>().type = LightType.Directional;
                light.transform.rotation = Quaternion.Euler(50f, -30f, 0f);
                SceneManager.MoveGameObjectToScene(light, scene);

                EditorSceneManager.SaveScene(scene, scenePath);
            }
            finally
            {
                EditorSceneManager.CloseScene(scene, true);
            }

            AssetDatabase.ImportAsset(scenePath, ImportAssetOptions.ForceSynchronousImport);
            return scenePath;
        }

        private static string WriteNotes(Plan plan, string name, string scenePath)
        {
            try
            {
                string folder = StagingRoot + "/" + Sanitize(name);
                Directory.CreateDirectory(folder);
                string path = folder + "/" + Sanitize(name) + " read me.txt";

                var text = new System.Text.StringBuilder();
                text.AppendLine(name);
                text.AppendLine("Packed with WPFMA-SDK on " + DateTime.Now.ToString("yyyy-MM-dd HH:mm"));
                text.AppendLine();
                text.AppendLine("Prefab: " + plan.PrefabPath);
                if (scenePath != null)
                    text.AppendLine("Scene:  " + scenePath);
                text.AppendLine();

                if (plan.PackageRequirements.Count == 0)
                {
                    text.AppendLine("No extra packages are needed.");
                }
                else
                {
                    text.AppendLine("Install these first, or the avatar opens with missing scripts and materials:");
                    foreach (var requirement in plan.PackageRequirements)
                        text.AppendLine("  - " + requirement);
                }

                File.WriteAllText(path, text.ToString());
                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport);
                return path;
            }
            catch (Exception)
            {
                return null;
            }
        }

        private static string ResolvePrefabPath(GameObject avatar)
        {
            string direct = AssetDatabase.GetAssetPath(avatar);
            if (!string.IsNullOrEmpty(direct))
                return direct;

            var source = PrefabUtility.GetCorrespondingObjectFromSource(avatar);
            if (source != null)
            {
                string path = AssetDatabase.GetAssetPath(source);
                if (!string.IsNullOrEmpty(path))
                    return path;
            }

            return null;
        }

        private static string PackageOf(string path)
        {
            var parts = path.Split('/');
            if (parts.Length < 2)
                return null;

            string id = parts[1];
            var info = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(path);
            if (info == null)
                return id;

            return string.IsNullOrEmpty(info.displayName) || info.displayName == id
                ? id + " " + info.version
                : info.displayName + " (" + id + ") " + info.version;
        }

        private static string LabelFor(string path)
        {
            switch (Path.GetExtension(path).ToLowerInvariant())
            {
                case ".png":
                case ".jpg":
                case ".jpeg":
                case ".tga":
                case ".psd":
                case ".exr": return "Textures";
                case ".mat": return "Materials";
                case ".anim": return "Animation clips";
                case ".controller":
                case ".overridecontroller": return "Animator controllers";
                case ".fbx":
                case ".obj":
                case ".blend": return "Models";
                case ".shader":
                case ".shadergraph":
                case ".cginc":
                case ".hlsl": return "Shaders";
                case ".asset": return "Settings assets";
                case ".mask": return "Avatar masks";
                case ".cs": return "Scripts";
                case ".prefab": return "Prefabs";
                case ".wav":
                case ".mp3":
                case ".ogg": return "Audio";
                default: return "Other";
            }
        }

        private static string Sanitize(string name)
        {
            return WPFMAPaths.SafeFileName(name);
        }
    }
}
#endif
