using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

// Measures where a card part is actually visible, using the texture's alpha channel (the same test the card and
// highlight shaders clip with) instead of the mesh, whose quad is padded around the printed card.
//
// Every rectangle is expressed as (a, b) coordinates in the card's local space, where a = dot(local, axisA) and
// b = dot(local, axisB). axisA/axisB are the peek rig's short/long axes (GrabbableHand.peekAxisA*/peekAxisB*).
public static class CardSilhouette
{
    public const float DefaultCutoff = 0.5f;
    public const int AtlasColumns = 13; // card_atlas.png: 13 ranks x 4 suits
    public const int AtlasRows = 4;

    public struct Rect2
    {
        public Vector2 min;
        public Vector2 max;
        public Vector2 Center { get { return (min + max) * 0.5f; } }
        public Vector2 Size { get { return max - min; } }
    }

    private static readonly Dictionary<string, Texture2D> DecodedTextures = new Dictionary<string, Texture2D>();

    // Card-local position of every vertex with the bones exactly as they are now (the prefab's rest pose).
    public static Vector3[] RestLocalVertices(SkinnedMeshRenderer smr, Transform card)
    {
        Mesh mesh = smr.sharedMesh;
        Vector3[] vertices = mesh.vertices;
        BoneWeight[] weights = mesh.boneWeights;
        Matrix4x4[] bindposes = mesh.bindposes;
        Transform[] bones = smr.bones;

        Matrix4x4[] boneToCard = new Matrix4x4[bones.Length];
        for (int i = 0; i < bones.Length; i++)
            boneToCard[i] = card.worldToLocalMatrix * bones[i].localToWorldMatrix * bindposes[i];

        Vector3[] result = new Vector3[vertices.Length];
        for (int v = 0; v < vertices.Length; v++)
        {
            BoneWeight w = weights[v];
            Vector3 p = Vector3.zero;
            if (w.weight0 > 0f) p += w.weight0 * boneToCard[w.boneIndex0].MultiplyPoint3x4(vertices[v]);
            if (w.weight1 > 0f) p += w.weight1 * boneToCard[w.boneIndex1].MultiplyPoint3x4(vertices[v]);
            if (w.weight2 > 0f) p += w.weight2 * boneToCard[w.boneIndex2].MultiplyPoint3x4(vertices[v]);
            if (w.weight3 > 0f) p += w.weight3 * boneToCard[w.boneIndex3].MultiplyPoint3x4(vertices[v]);
            result[v] = p;
        }
        return result;
    }

    public static bool TryMeasure(SkinnedMeshRenderer smr, Transform card, Vector3 axisA, Vector3 axisB,
        float cutoff, out Rect2 rect)
    {
        return TryMeasure(smr.sharedMesh, RestLocalVertices(smr, card), MainMaterial(smr), axisA, axisB, cutoff, out rect);
    }

    // The visible rectangle of a mesh whose card-local vertices are given. Only the texture window the mesh's UVs
    // cover is considered, so a two-panel atlas (front | back) is measured one panel at a time.
    public static bool TryMeasure(Mesh mesh, Vector3[] localVertices, Material material, Vector3 axisA, Vector3 axisB,
        float cutoff, out Rect2 rect)
    {
        return TryMeasure(mesh, localVertices, material, axisA, axisB, cutoff, Vector2.zero, out rect);
    }

    // uvShift slides the sampled window across the texture (for atlas cells other than the one the mesh maps to);
    // the result is still expressed on the mesh.
    public static bool TryMeasure(Mesh mesh, Vector3[] localVertices, Material material, Vector3 axisA, Vector3 axisB,
        float cutoff, Vector2 uvShift, out Rect2 rect)
    {
        rect = new Rect2();
        if (material == null || !material.HasProperty("_MainTex"))
            return false;
        Texture2D texture = Decode(material.GetTexture("_MainTex"));
        if (texture == null)
            return false;
        Vector2 scale = material.mainTextureScale;
        Vector2 offset = material.mainTextureOffset;

        Vector2[] uv = mesh.uv;
        Vector2 uvMin = uv[0], uvMax = uv[0];
        for (int i = 1; i < uv.Length; i++)
        {
            uvMin = Vector2.Min(uvMin, uv[i]);
            uvMax = Vector2.Max(uvMax, uv[i]);
        }

        // opaque texel bounds inside the window, in sampled-UV space
        int width = texture.width, height = texture.height;
        Color32[] pixels = texture.GetPixels32();
        byte threshold = (byte)Mathf.CeilToInt(cutoff * 255f);
        int minX = int.MaxValue, minY = int.MaxValue, maxX = -1, maxY = -1;
        for (int y = 0; y < height; y++)
        {
            float v = ((y + 0.5f) / height - offset.y) / scale.y;
            v -= uvShift.y;
            if (v < uvMin.y || v > uvMax.y) continue;
            for (int x = 0; x < width; x++)
            {
                float u = ((x + 0.5f) / width - offset.x) / scale.x;
                u -= uvShift.x;
                if (u < uvMin.x || u > uvMax.x) continue;
                if (pixels[y * width + x].a < threshold) continue;
                if (x < minX) minX = x;
                if (x > maxX) maxX = x;
                if (y < minY) minY = y;
                if (y > maxY) maxY = y;
            }
        }
        if (maxX < 0)
            return false;

        Vector2 uvLo = new Vector2((minX / (float)width - offset.x) / scale.x, (minY / (float)height - offset.y) / scale.y) - uvShift;
        Vector2 uvHi = new Vector2(((maxX + 1) / (float)width - offset.x) / scale.x, ((maxY + 1) / (float)height - offset.y) / scale.y) - uvShift;

        // UV -> (a, b): affine fit through the three most independent vertices
        int i0 = 0, i1 = 0, i2 = 0;
        float best = -1f;
        for (int i = 1; i < uv.Length; i++)
        {
            float d = (uv[i] - uv[0]).sqrMagnitude;
            if (d > best) { best = d; i1 = i; }
        }
        best = -1f;
        Vector2 d1 = uv[i1] - uv[i0];
        for (int i = 0; i < uv.Length; i++)
        {
            Vector2 d = uv[i] - uv[i0];
            float area = Mathf.Abs(d1.x * d.y - d1.y * d.x);
            if (area > best) { best = area; i2 = i; }
        }
        Vector2 d2 = uv[i2] - uv[i0];
        float det = d1.x * d2.y - d1.y * d2.x;
        if (Mathf.Abs(det) < 1e-12f)
            return false;

        Vector2 l0 = Project(localVertices[i0], axisA, axisB);
        Vector2 e1 = Project(localVertices[i1], axisA, axisB) - l0;
        Vector2 e2 = Project(localVertices[i2], axisA, axisB) - l0;
        // a UV offset d = s*d1 + t*d2 lands at local l0 + s*e1 + t*e2
        Vector2[] corners = { uvLo, new Vector2(uvHi.x, uvLo.y), uvHi, new Vector2(uvLo.x, uvHi.y) };
        Vector2 lo = new Vector2(float.MaxValue, float.MaxValue), hi = -lo;
        foreach (Vector2 corner in corners)
        {
            Vector2 d = corner - uv[i0];
            float s = (d.x * d2.y - d.y * d2.x) / det;
            float t = (d1.x * d.y - d1.y * d.x) / det;
            Vector2 local = l0 + s * e1 + t * e2;
            lo = Vector2.Min(lo, local);
            hi = Vector2.Max(hi, local);
        }
        rect = new Rect2 { min = lo, max = hi };
        return true;
    }

    // Visible rectangle of every cell of a columns x rows atlas, in the mesh's own space (the mesh maps to one cell;
    // the others are sampled by sliding the window). PlayingCard picks the cell at runtime, so the union over all cells
    // is what the card can look like.
    public static Rect2[] MeasureAtlasCells(Mesh mesh, Vector3[] localVertices, Material material, Vector3 axisA,
        Vector3 axisB, float cutoff, int columns, int rows)
    {
        Vector2[] uv = mesh.uv;
        Vector2 uvMin = uv[0];
        foreach (Vector2 u in uv) uvMin = Vector2.Min(uvMin, u);
        int baseColumn = Mathf.RoundToInt(uvMin.x * columns);
        int baseRow = Mathf.RoundToInt(uvMin.y * rows);

        Rect2[] cells = new Rect2[columns * rows];
        for (int row = 0; row < rows; row++)
        {
            for (int column = 0; column < columns; column++)
            {
                Vector2 shift = new Vector2((column - baseColumn) / (float)columns, (row - baseRow) / (float)rows);
                if (!TryMeasure(mesh, localVertices, material, axisA, axisB, cutoff, shift, out cells[row * columns + column]))
                    throw new System.InvalidOperationException("Atlas cell " + column + "," + row + " has no opaque pixels.");
            }
        }
        return cells;
    }

    public static Rect2 Union(Rect2[] rects)
    {
        Rect2 union = rects[0];
        for (int i = 1; i < rects.Length; i++)
        {
            union.min = Vector2.Min(union.min, rects[i].min);
            union.max = Vector2.Max(union.max, rects[i].max);
        }
        return union;
    }

    // The (a, b) position of a mesh vertex with the given UV, using the same fit as TryMeasure.
    public static bool TryUvToLocal(Mesh mesh, Vector3[] localVertices, Vector3 axisA, Vector3 axisB,
        out System.Func<Vector2, Vector3> map)
    {
        map = null;
        Vector2[] uv = mesh.uv;
        int i0 = 0, i1 = 0, i2 = 0;
        float best = -1f;
        for (int i = 1; i < uv.Length; i++)
        {
            float d = (uv[i] - uv[0]).sqrMagnitude;
            if (d > best) { best = d; i1 = i; }
        }
        best = -1f;
        Vector2 d1 = uv[i1] - uv[i0];
        for (int i = 0; i < uv.Length; i++)
        {
            Vector2 d = uv[i] - uv[i0];
            float area = Mathf.Abs(d1.x * d.y - d1.y * d.x);
            if (area > best) { best = area; i2 = i; }
        }
        Vector2 d2 = uv[i2] - uv[i0];
        float det = d1.x * d2.y - d1.y * d2.x;
        if (Mathf.Abs(det) < 1e-12f)
            return false;

        Vector3 p0 = localVertices[i0];
        Vector3 e1 = localVertices[i1] - p0;
        Vector3 e2 = localVertices[i2] - p0;
        Vector2 uv0 = uv[i0];
        map = q =>
        {
            Vector2 d = q - uv0;
            float s = (d.x * d2.y - d.y * d2.x) / det;
            float t = (d1.x * d.y - d1.y * d.x) / det;
            return p0 + s * e1 + t * e2;
        };
        return true;
    }

    public static Vector2 Project(Vector3 local, Vector3 axisA, Vector3 axisB)
    {
        return new Vector2(Vector3.Dot(local, axisA), Vector3.Dot(local, axisB));
    }

    public static Material MainMaterial(SkinnedMeshRenderer smr)
    {
        Material[] materials = smr.sharedMaterials;
        return materials.Length > 0 ? materials[0] : null;
    }

    // Reads the file itself, so the result does not depend on the import's Read/Write or compression settings.
    private static Texture2D Decode(Texture texture)
    {
        if (texture == null)
            return null;
        string assetPath = AssetDatabase.GetAssetPath(texture);
        if (string.IsNullOrEmpty(assetPath))
            return null;
        Texture2D cached;
        if (DecodedTextures.TryGetValue(assetPath, out cached) && cached != null)
            return cached;
        Texture2D decoded = new Texture2D(2, 2, TextureFormat.RGBA32, false);
        if (!ImageConversion.LoadImage(decoded, System.IO.File.ReadAllBytes(System.IO.Path.GetFullPath(assetPath))))
            return null;
        DecodedTextures[assetPath] = decoded;
        return decoded;
    }
}
