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

// Measures whether the four rank indices of a dealt hand (top-left and bottom-right of each hole card) are visible
// from above, with the winner / hand highlight rings shown.
//
// Everything is computed in the Hand prefab's local space from the skinned geometry itself (CardSilhouette), not from
// the GameObject transforms of the renderers: a SkinnedMeshRenderer is drawn by its bones, and the highlight meshes
// are skinned to their card's bones, so a card's pose is what places both the card and its rings.
//
// Occlusion model: viewed from +y, a layer hides everything beneath it that lies under its footprint.
//  - a card hides lower layers under its printed face,
//  - a highlight ring hides lower layers under the band between its outline and its card.
public static class CardNumberVisibility
{
    // Where the index sits inside an atlas cell, as fractions of the cell (u from the left, v down from the top).
    // Measured from the ink of every rank in card_atlas.png (rank plus suit pip): u 0.04-0.19, v 0.06-0.28 (the
    // widest is the club 10). The bottom-right index is the same printed 180 degrees around the cell center.
    public static readonly Rect TopLeftIndex = new Rect(0.04f, 0.06f, 0.15f, 0.22f);

    public const float Tolerance = 1e-6f;

    public struct Pose
    {
        public Vector3 position;
        public float yaw; // degrees about the hand's up axis
    }

    public struct Layer
    {
        public string name;
        public Vector2[] outer; // xz footprint in hand space
        public Vector2[] hole; // optional xz footprint carved out of the footprint (a ring), else null
        public float height;
    }

    public class Report
    {
        public readonly List<string> hidden = new List<string>();
        public float worstClearance = float.MaxValue; // mm of the smallest margin around any index; < 0 is covered
        public bool AllVisible { get { return hidden.Count == 0; } }
    }

    public static void ApplyPose(GameObject root, int cardIndex, Pose pose)
    {
        foreach (string path in new[] { "Card", "Highlight/HighlightCard", "HighlightHand/HighlightCard" })
        {
            Transform t = root.transform.Find(path + cardIndex);
            if (t == null) continue;
            // highlights sit exactly on their card (CardRigRecenter requires it)
            t.localPosition = pose.position;
            t.localRotation = Quaternion.Euler(0f, pose.yaw, 0f);
        }
    }

    public static Pose ReadPose(GameObject root, int cardIndex)
    {
        Transform t = root.transform.Find("Card" + cardIndex);
        return new Pose { position = t.localPosition, yaw = Normalize(t.localEulerAngles.y) };
    }

    private static float Normalize(float degrees)
    {
        return Mathf.DeltaAngle(0f, degrees);
    }

    // The pose-independent geometry of a hand: every footprint in its card's local space.
    public class Rig
    {
        public class LocalLayer
        {
            public string name;
            public int cardIndex;
            public bool isRing;
            public string set;
            public Vector3[] outer;
            public Vector3[] hole; // card face carved out of a ring
            public float height; // card-local height above the card origin
        }
        public readonly List<LocalLayer> layers = new List<LocalLayer>();
        public readonly List<LocalLayer> regions = new List<LocalLayer>();
    }

    public static Rig Build(GameObject root)
    {
        GrabbableHand hand = root.GetComponent<GrabbableHand>();
        var rig = new Rig();
        for (int i = 0; i < 2; i++)
        {
            Transform card = root.transform.Find("Card" + i);
            Vector3 axisA = i == 0 ? hand.peekAxisA0 : hand.peekAxisA1;
            Vector3 axisB = i == 0 ? hand.peekAxisB0 : hand.peekAxisB1;

            var front = card.Find("Front").GetComponent<SkinnedMeshRenderer>();
            Vector3[] local = CardSilhouette.RestLocalVertices(front, card);
            System.Func<Vector2, Vector3> uvToLocal;
            if (!CardSilhouette.TryUvToLocal(front.sharedMesh, local, axisA, axisB, out uvToLocal))
                throw new System.InvalidOperationException("Card" + i + "/Front UVs are degenerate");

            Vector2 uvMin = front.sharedMesh.uv[0], uvMax = uvMin;
            foreach (Vector2 uv in front.sharedMesh.uv) { uvMin = Vector2.Min(uvMin, uv); uvMax = Vector2.Max(uvMax, uv); }
            Vector2 cell = uvMax - uvMin;

            Vector3[] face = { Cell(uvToLocal, uvMin, cell, 0, 0), Cell(uvToLocal, uvMin, cell, 1, 0), Cell(uvToLocal, uvMin, cell, 1, 1), Cell(uvToLocal, uvMin, cell, 0, 1) };
            float frontHeight = MeanY(local);
            rig.layers.Add(new Rig.LocalLayer { name = "Card" + i, cardIndex = i, outer = face, height = frontHeight });

            // the two rank indices: u from the left / v from the top of the atlas cell
            Rect tl = TopLeftIndex;
            Rect br = new Rect(1f - tl.xMax, 1f - tl.yMax, tl.width, tl.height);
            rig.regions.Add(Region("Card" + i + " top-left index", i, uvToLocal, uvMin, cell, tl, frontHeight));
            rig.regions.Add(Region("Card" + i + " bottom-right index", i, uvToLocal, uvMin, cell, br, frontHeight));

            foreach (string set in new[] { "Highlight", "HighlightHand" })
            {
                var ring = root.transform.Find(set + "/HighlightCard" + i + "/FrontBlank").GetComponent<SkinnedMeshRenderer>();
                Vector3[] ringLocal = CardSilhouette.RestLocalVertices(ring, card);
                CardSilhouette.Rect2 rect;
                if (!CardSilhouette.TryMeasure(ring.sharedMesh, ringLocal, CardSilhouette.MainMaterial(ring), axisA, axisB,
                        CardSilhouette.DefaultCutoff, out rect))
                    throw new System.InvalidOperationException(set + "/HighlightCard" + i + " has no opaque pixels");
                Vector3 normalOffset = NormalOffset(ringLocal, axisA, axisB);
                rig.layers.Add(new Rig.LocalLayer
                {
                    name = set + "/HighlightCard" + i, cardIndex = i, isRing = true, set = set, hole = face,
                    height = MeanY(ringLocal),
                    outer = new[]
                    {
                        Rebuild(rect.min.x, rect.min.y, axisA, axisB, normalOffset), Rebuild(rect.max.x, rect.min.y, axisA, axisB, normalOffset),
                        Rebuild(rect.max.x, rect.max.y, axisA, axisB, normalOffset), Rebuild(rect.min.x, rect.max.y, axisA, axisB, normalOffset),
                    },
                });
            }
        }
        return rig;
    }

    // Measures the hand as it is currently posed on `root`.
    public static Report Measure(GameObject root, bool winnerRings, bool handRings, float marginMeters)
    {
        return Evaluate(Build(root), ReadPose(root, 0), ReadPose(root, 1), winnerRings, handRings, marginMeters);
    }

    // winnerRings / handRings = which ring sets count as lit: "Highlight" (winner) and "HighlightHand".
    public static Report Evaluate(Rig rig, Pose pose0, Pose pose1, bool winnerRings, bool handRings, float marginMeters)
    {
        Matrix4x4[] cardToHand =
        {
            Matrix4x4.TRS(pose0.position, Quaternion.Euler(0f, pose0.yaw, 0f), Vector3.one),
            Matrix4x4.TRS(pose1.position, Quaternion.Euler(0f, pose1.yaw, 0f), Vector3.one),
        };

        var layers = new List<Layer>();
        foreach (Rig.LocalLayer l in rig.layers)
        {
            if (l.isRing && (l.set == "Highlight" ? !winnerRings : !handRings)) continue;
            Matrix4x4 m = cardToHand[l.cardIndex];
            layers.Add(new Layer
            {
                name = l.name, outer = ToXz(m, l.outer), hole = l.hole == null ? null : ToXz(m, l.hole),
                height = m.MultiplyPoint3x4(new Vector3(0f, l.height, 0f)).y,
            });
        }

        var report = new Report();
        foreach (Rig.LocalLayer r in rig.regions)
        {
            Matrix4x4 m = cardToHand[r.cardIndex];
            Vector2[] area = ToXz(m, r.outer);
            float height = m.MultiplyPoint3x4(new Vector3(0f, r.height, 0f)).y;
            float clearance = float.MaxValue;
            string culprit = null;
            foreach (Layer layer in layers)
            {
                if (layer.height <= height + Tolerance) continue; // beneath (or level with) the index
                float c = Clearance(area, layer);
                if (c < marginMeters && c < clearance) { clearance = c; culprit = layer.name; }
            }
            if (culprit != null)
                report.hidden.Add(r.name + " is " + (clearance < 0f ? "covered" : "within " + (clearance * 1000f).ToString("F1") + " mm") + " by " + culprit);
            report.worstClearance = Mathf.Min(report.worstClearance, culprit == null ? marginMeters * 1000f : clearance * 1000f);
        }
        return report;
    }

    // ---- geometry ----

    private static Vector3 Cell(System.Func<Vector2, Vector3> uvToLocal, Vector2 uvMin, Vector2 cell, float u, float v)
    {
        return uvToLocal(new Vector2(uvMin.x + u * cell.x, uvMin.y + v * cell.y));
    }

    private static Rig.LocalLayer Region(string name, int cardIndex, System.Func<Vector2, Vector3> uvToLocal,
        Vector2 uvMin, Vector2 cell, Rect r, float height)
    {
        // r is in (u from left, v from top); the atlas v axis points up
        return new Rig.LocalLayer
        {
            name = name, cardIndex = cardIndex, height = height,
            outer = new[]
            {
                Cell(uvToLocal, uvMin, cell, r.xMin, 1f - r.yMin), Cell(uvToLocal, uvMin, cell, r.xMax, 1f - r.yMin),
                Cell(uvToLocal, uvMin, cell, r.xMax, 1f - r.yMax), Cell(uvToLocal, uvMin, cell, r.xMin, 1f - r.yMax),
            },
        };
    }

    private static Vector2[] ToXz(Matrix4x4 m, Vector3[] local)
    {
        var result = new Vector2[local.Length];
        for (int i = 0; i < local.Length; i++)
        {
            Vector3 p = m.MultiplyPoint3x4(local[i]);
            result[i] = new Vector2(p.x, p.z);
        }
        return result;
    }

    private static float MeanY(Vector3[] local)
    {
        float sum = 0f;
        foreach (Vector3 v in local) sum += v.y;
        return sum / local.Length;
    }

    // The component of the vertices that lies along neither in-plane axis (the card's thickness direction).
    private static Vector3 NormalOffset(Vector3[] local, Vector3 axisA, Vector3 axisB)
    {
        Vector3 mean = Vector3.zero;
        foreach (Vector3 v in local) mean += v;
        mean /= local.Length;
        return mean - axisA * Vector3.Dot(mean, axisA) - axisB * Vector3.Dot(mean, axisB);
    }

    private static Vector3 Rebuild(float a, float b, Vector3 axisA, Vector3 axisB, Vector3 normalOffset)
    {
        return axisA * a + axisB * b + normalOffset;
    }

    // Smallest distance from any corner/edge sample of the index area to the layer's covered footprint; negative when
    // some part of the area is under the layer. The margin is therefore "how far the index is from being hidden".
    private static float Clearance(Vector2[] area, Layer layer)
    {
        float worst = float.MaxValue;
        const int N = 6;
        for (int iy = 0; iy <= N; iy++)
        for (int ix = 0; ix <= N; ix++)
        {
            Vector2 p = Bilinear(area, ix / (float)N, iy / (float)N);
            float d = SignedDistanceInside(p, layer); // positive = inside the covered footprint
            worst = Mathf.Min(worst, -d);
        }
        return worst;
    }

    private static float SignedDistanceInside(Vector2 p, Layer layer)
    {
        float inside = SignedInside(p, layer.outer);
        if (layer.hole == null) return inside;
        float hole = SignedInside(p, layer.hole);
        return Mathf.Min(inside, -hole);
    }

    // > 0 inside the (convex) polygon by that distance, < 0 outside by that distance
    private static float SignedInside(Vector2 p, Vector2[] poly)
    {
        float sign = PolygonArea(poly) >= 0f ? 1f : -1f;
        float minDist = float.MaxValue;
        bool inside = true;
        for (int i = 0; i < poly.Length; i++)
        {
            Vector2 a = poly[i], b = poly[(i + 1) % poly.Length];
            Vector2 edge = b - a;
            Vector2 normal = new Vector2(-edge.y, edge.x).normalized * sign;
            float d = Vector2.Dot(p - a, normal);
            if (d < 0f) inside = false;
            minDist = Mathf.Min(minDist, Mathf.Abs(d));
        }
        // outside: signed distance to the polygon boundary (corner cases approximated by the nearest edge line)
        return inside ? minDist : -DistanceToBoundary(p, poly);
    }

    private static float DistanceToBoundary(Vector2 p, Vector2[] poly)
    {
        float best = float.MaxValue;
        for (int i = 0; i < poly.Length; i++)
        {
            Vector2 a = poly[i], b = poly[(i + 1) % poly.Length];
            Vector2 ab = b - a;
            float t = Mathf.Clamp01(Vector2.Dot(p - a, ab) / ab.sqrMagnitude);
            best = Mathf.Min(best, (p - (a + ab * t)).magnitude);
        }
        return best;
    }

    private static float PolygonArea(Vector2[] poly)
    {
        float sum = 0f;
        for (int i = 0; i < poly.Length; i++)
        {
            Vector2 a = poly[i], b = poly[(i + 1) % poly.Length];
            sum += a.x * b.y - b.x * a.y;
        }
        return sum * 0.5f;
    }

    private static Vector2 Bilinear(Vector2[] quad, float s, float t)
    {
        Vector2 top = Vector2.Lerp(quad[0], quad[1], s);
        Vector2 bottom = Vector2.Lerp(quad[3], quad[2], s);
        return Vector2.Lerp(top, bottom, t);
    }

    // ---- animation clips ----

    // The Card0/Card1 pose a clip ends on (x/y/z and yaw), read straight from its curves.
    public static bool TryReadClipPose(AnimationClip clip, int cardIndex, float time, out Pose pose)
    {
        string path = "Card" + cardIndex;
        pose = new Pose();
        float x, y, z, yaw;
        if (!Sample(clip, path, "m_LocalPosition.x", time, out x) || !Sample(clip, path, "m_LocalPosition.y", time, out y) ||
            !Sample(clip, path, "m_LocalPosition.z", time, out z) || !Sample(clip, path, "localEulerAnglesRaw.y", time, out yaw))
            return false;
        pose = new Pose { position = new Vector3(x, y, z), yaw = Normalize(yaw) };
        return true;
    }

    private static bool Sample(AnimationClip clip, string path, string property, float time, out float value)
    {
        AnimationCurve curve = AnimationUtility.GetEditorCurve(clip, EditorCurveBinding.FloatCurve(path, typeof(Transform), property));
        value = curve != null && curve.length > 0 ? curve.Evaluate(time) : 0f;
        return curve != null && curve.length > 0;
    }
}
