// 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 UnityEditor;

namespace WPFMA.Vrca
{
    internal static class WPFMATextureImportRules
    {
        internal struct Rule
        {
            public bool NormalMap;
            public bool Colour;
            public int SourceSize;
        }

        private static readonly Dictionary<string, Rule> Pending =
            new Dictionary<string, Rule>(StringComparer.OrdinalIgnoreCase);

        internal static void Register(string assetPath, Rule rule)
        {
            Pending[Normalize(assetPath)] = rule;
        }

        internal static void Forget(string assetPath)
        {
            Pending.Remove(Normalize(assetPath));
        }

        internal static void Apply(string assetPath, TextureImporter importer)
        {
            if (importer == null)
                return;

            Rule rule;
            string key = Normalize(assetPath);
            if (!Pending.TryGetValue(key, out rule))
                return;

            Pending.Remove(key);

            if (rule.NormalMap)
                importer.textureType = TextureImporterType.NormalMap;
            else
                importer.sRGBTexture = rule.Colour;

            if (rule.Colour)
                importer.alphaIsTransparency = true;

            if (rule.SourceSize > importer.maxTextureSize)
                importer.maxTextureSize = UnityEngine.Mathf.NextPowerOfTwo(rule.SourceSize);

            if (importer.mipmapEnabled)
            {
                importer.streamingMipmaps = true;
                importer.streamingMipmapsPriority = 0;
            }
        }

        private static string Normalize(string path)
        {
            return string.IsNullOrEmpty(path) ? string.Empty : path.Replace('\\', '/');
        }
    }

    internal sealed class WPFMATexturePostprocessor : AssetPostprocessor
    {
        private void OnPreprocessTexture()
        {
            WPFMATextureImportRules.Apply(assetPath, assetImporter as TextureImporter);
        }
    }
}
#endif
