using System.IO;
using UnityEditor;
using UnityEngine;

namespace MajacloudSdk.Editor
{
    /// <summary>
    /// Sprites for the demo scenes: a generated rounded rectangle (9-sliced, so one
    /// texture gives every corner radius) and the bundled Majacloud logo.
    /// </summary>
    internal static class SoftArt
    {
        /// <summary>Corner radius baked into the texture, in pixels. Image.pixelsPerUnitMultiplier scales it.</summary>
        public const int CornerPixels = 56;
        private const int Size = 128;

        private static Sprite _rounded;
        private static Sprite _logo;

        public static string RoundedPath => MajacloudEditorPaths.ArtPath + "/Rounded.png";
        public static string LogoPath => MajacloudEditorPaths.ArtPath + "/MajacloudLogo.png";

        public static Sprite Rounded
        {
            get
            {
                if (_rounded == null) _rounded = AssetDatabase.LoadAssetAtPath<Sprite>(RoundedPath);
                return _rounded;
            }
        }

        public static Sprite Logo
        {
            get
            {
                if (_logo == null) _logo = AssetDatabase.LoadAssetAtPath<Sprite>(LogoPath);
                return _logo;
            }
        }

        public static void Ensure()
        {
            MajacloudEditorPaths.EnsureFolder(MajacloudEditorPaths.ArtPath);
            if (!File.Exists(RoundedPath))
            {
                File.WriteAllBytes(RoundedPath, CreateRoundedPng());
                AssetDatabase.ImportAsset(RoundedPath, ImportAssetOptions.ForceSynchronousImport);
            }
            ConfigureSprite(RoundedPath, CornerPixels, false);
            if (File.Exists(LogoPath)) ConfigureSprite(LogoPath, 0, true);
            else Debug.LogWarning("[Majacloud] Logo not found at " + LogoPath + "; the demo scenes will show no logo.");
            _rounded = null;
            _logo = null;
        }

        private static byte[] CreateRoundedPng()
        {
            var texture = new Texture2D(Size, Size, TextureFormat.RGBA32, false);
            var pixels = new Color32[Size * Size];
            float radius = CornerPixels;
            for (int y = 0; y < Size; y++)
            {
                for (int x = 0; x < Size; x++)
                {
                    var point = new Vector2(x + 0.5f, y + 0.5f);
                    var nearest = new Vector2(Mathf.Clamp(point.x, radius, Size - radius), Mathf.Clamp(point.y, radius, Size - radius));
                    float alpha = Mathf.Clamp01(radius - Vector2.Distance(point, nearest) + 0.5f);
                    pixels[y * Size + x] = new Color32(255, 255, 255, (byte)Mathf.RoundToInt(alpha * 255f));
                }
            }
            texture.SetPixels32(pixels);
            texture.Apply();
            var png = texture.EncodeToPNG();
            Object.DestroyImmediate(texture);
            return png;
        }

        private static void ConfigureSprite(string path, int border, bool mipmaps)
        {
            if (!(AssetImporter.GetAtPath(path) is TextureImporter importer)) return;
            importer.textureType = TextureImporterType.Sprite;
            importer.spriteImportMode = SpriteImportMode.Single;
            var settings = new TextureImporterSettings();
            importer.ReadTextureSettings(settings);
            settings.spriteMeshType = SpriteMeshType.FullRect;
            importer.SetTextureSettings(settings);
            importer.spriteBorder = new Vector4(border, border, border, border);
            importer.spritePixelsPerUnit = 100;
            importer.mipmapEnabled = mipmaps;
            importer.alphaIsTransparency = true;
            importer.filterMode = mipmaps ? FilterMode.Trilinear : FilterMode.Bilinear;
            importer.wrapMode = TextureWrapMode.Clamp;
            importer.textureCompression = TextureImporterCompression.Uncompressed;
            importer.SaveAndReimport();
        }
    }
}
