using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using VRC.SDKBase;

public class HandCalibrationTests
{
    private const string Key = HandCalibration.PersistenceHandOffsetKey;

    private readonly List<GameObject> objects = new List<GameObject>();
    private VrcRuntimeFake runtime;
    private PokerChipPile pile;
    private HandCalibration calibration;
    private PhysicalRaisePile first;
    private PhysicalRaisePile second;
    private TMPro.TMP_Text label;

    [SetUp]
    public void SetUp()
    {
        runtime = new VrcRuntimeFake();
        runtime.Install();
        runtime.VrUsers[runtime.LocalPlayer.playerId] = true;

        int[] values = { 5 };
        var poolObject = Spawn("Pool");
        LocalObjectPool pool = poolObject.AddComponent<LocalObjectPool>();
        pool.denomination = 5;
        pool.Pool = new GameObject[40];
        for (int i = 0; i < pool.Pool.Length; i++)
        {
            pool.Pool[i] = Spawn("Chip" + i);
            pool.Pool[i].transform.SetParent(poolObject.transform);
        }
        VrcRuntimeFake.InvokeNoArg(pool, "Start");

        GameObject pileObject = Spawn("CalibrationPile");
        pileObject.transform.position = new Vector3(-0.3f, 1f, 0.5f);
        pile = pileObject.AddComponent<PokerChipPile>();
        pile.denominationValues = values;
        pile.denominationPools = new[] { pool };
        pile.stackHeight = 10;
        pile.denominationOffsets = new[] { Vector3.zero };
        GameObject pileText = Spawn("PileText");
        pileText.transform.SetParent(pileObject.transform);
        pile.text = pileText.AddComponent<TMPro.TextMeshPro>();
        pile.textGameObject = pileText;
        VrcRuntimeFake.InvokeNoArg(pile, "Start");

        first = Spawn("PileA").AddComponent<PhysicalRaisePile>();
        second = Spawn("PileB").AddComponent<PhysicalRaisePile>();

        GameObject labelObject = Spawn("Label");
        label = labelObject.AddComponent<TMPro.TextMeshPro>();

        calibration = Spawn("Calibration").AddComponent<HandCalibration>();
        calibration.calibrationPile = pile;
        calibration.piles = new[] { first, second };
        calibration.label = label;
        VrcRuntimeFake.InvokeNoArg(calibration, "Start");
        calibration._InitialFill();
    }

    [TearDown]
    public void TearDown()
    {
        runtime.Uninstall();
        for (int i = objects.Count - 1; i >= 0; i--) if (objects[i]) Object.DestroyImmediate(objects[i]);
        objects.Clear();
    }

    private GameObject Spawn(string name)
    {
        GameObject go = new GameObject(name);
        objects.Add(go);
        return go;
    }

    private Vector3 TopChipCenter()
    {
        Vector3 column = pile.GetDenominationColumnWorldPosition(0, 0);
        float chip = pile.chipHeight * Mathf.Abs(pile.transform.lossyScale.y);
        return new Vector3(column.x, pile.GetDenominationColumnTopWorldY(0, 0) - chip * 0.5f, column.z);
    }

    /// <summary>Left hand a plausible controller-to-palm distance from the top chip, with some wrist twist.</summary>
    private void PlaceLeftHand(Quaternion rotation)
    {
        Vector3 position = TopChipCenter() + new Vector3(0.02f, -0.1f, -0.05f);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRCPlayerApi.TrackingDataType.LeftHand, position);
        runtime.SetTrackingRotation(runtime.LocalPlayer, VRCPlayerApi.TrackingDataType.LeftHand, rotation);
    }

    private static string Format(Vector3 v)
    {
        var c = System.Globalization.CultureInfo.InvariantCulture;
        return "(" + v.x.ToString("F3", c) + ", " + v.y.ToString("F3", c) + ", " + v.z.ToString("F3", c) + ")";
    }

    private Vector3 Saved { get { return (Vector3)runtime.Store[Key]; } }

    [Test]
    public void Start_FillsTheCalibrationPileWithOneColumnOfTenChips()
    {
        Assert.AreEqual(10, pile.GetDisplayedDenominationCount(0));
        Assert.AreEqual(1, pile.GetDenominationColumnCount(0));
        Assert.AreEqual(10, pile.GetDenominationColumnChipCount(0, 0));
    }

    [Test]
    public void Start_LabelExplainsTheStepsAndShowsTheDefaultOffset()
    {
        Assert.IsTrue(label.text.Contains("<b>Immersive betting calibration:</b>"), label.text);
        Assert.IsTrue(label.text.Contains("press that hand's button with the other hand"), label.text);
        Assert.IsTrue(label.text.Contains("Current offset: (0.000, 0.090, 0.050)"), label.text);
    }

    [Test]
    public void Calibrate_PutsTheSamplePointOnTheTopChipForEveryPile()
    {
        Quaternion rotation = Quaternion.Euler(10f, 20f, 35f);
        PlaceLeftHand(rotation);

        calibration._Calibrate();

        Vector3 handPosition = runtime.TrackingPositions[runtime.LocalPlayer.playerId + ":" + (int)VRCPlayerApi.TrackingDataType.LeftHand];
        foreach (PhysicalRaisePile target in new[] { first, second })
        {
            Vector3 point = PhysicalRaiseSelectionMath.HandPoint(handPosition, rotation, target._GetScaledHandOffset());
            Assert.AreEqual(0f, (point - TopChipCenter()).magnitude, 0.0005f);
        }
    }

    [Test]
    public void Calibrate_SavesThePlayerDataAndShowsTheNewCurrentOffset()
    {
        PlaceLeftHand(Quaternion.identity);

        calibration._Calibrate();

        Assert.IsTrue(runtime.Store.ContainsKey(Key));
        Assert.AreEqual(1, runtime.Writes.FindAll(w => w.StartsWith("SetVector3(" + Key)).Count);
        Assert.IsTrue(label.text.Contains("Current offset: " + Format(Saved)), label.text);
        Assert.IsTrue(label.text.Contains("Saved. Previous offset: (0.000, 0.090, 0.050)"), label.text);
    }

    [Test]
    public void Calibrate_SecondPressShowsTheFirstResultAsThePreviousValue()
    {
        PlaceLeftHand(Quaternion.identity);
        calibration._Calibrate();
        Vector3 firstResult = Saved;

        runtime.SetTrackingPosition(runtime.LocalPlayer, VRCPlayerApi.TrackingDataType.LeftHand,
            TopChipCenter() + new Vector3(0f, -0.15f, 0f));
        calibration._Calibrate();

        Assert.IsTrue(label.text.Contains("Previous offset: " + Format(firstResult)), label.text);
        Assert.IsTrue(label.text.Contains("Current offset: " + Format(Saved)), label.text);
        Assert.AreNotEqual(firstResult, Saved);
    }

    [Test]
    public void Calibrate_StoresTheOffsetNormalizedToTheReferenceEyeHeight()
    {
        Quaternion rotation = Quaternion.identity;
        PlaceLeftHand(rotation);
        runtime.EyeHeight = 1.6f;

        calibration._Calibrate();

        Vector3 measured = TopChipCenter() - runtime.TrackingPositions[runtime.LocalPlayer.playerId + ":" + (int)VRCPlayerApi.TrackingDataType.LeftHand];
        Assert.AreEqual(0f, (Saved - measured * 0.5f).magnitude, 0.0005f, "stored for 0.8m");

        runtime.EyeHeight = 0.8f;
        Assert.AreEqual(0f, (first._GetScaledHandOffset() - measured * 0.5f).magnitude, 0.0005f,
            "a 1.6m calibration applies at half size on a 0.8m avatar");
        runtime.EyeHeight = 1.6f;
        Assert.AreEqual(0f, (first._GetScaledHandOffset() - measured).magnitude, 0.0005f);
    }

    [Test]
    public void Calibrate_OnDesktopDoesNothing()
    {
        runtime.VrUsers[runtime.LocalPlayer.playerId] = false;
        PlaceLeftHand(Quaternion.identity);

        calibration._Calibrate();

        Assert.IsFalse(runtime.Store.ContainsKey(Key));
        Assert.AreEqual(0, runtime.Writes.Count);
        Assert.IsTrue(label.text.Contains("VR"), label.text);
    }

    [Test]
    public void Calibrate_HandAwayFromThePileIsRejectedWithoutWriting()
    {
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRCPlayerApi.TrackingDataType.LeftHand,
            TopChipCenter() + new Vector3(2f, 0f, 0f));

        calibration._Calibrate();

        Assert.IsFalse(runtime.Store.ContainsKey(Key));
        Assert.IsTrue(label.text.Contains("top chip"), label.text);
        Assert.AreEqual(0f, (first._GetScaledHandOffset() - first.handOffset).magnitude, 0.0001f);
    }

    [Test]
    public void Calibrate_PointingStraightUpIsRejectedWithoutWriting()
    {
        PlaceLeftHand(Quaternion.Euler(-85f, 0f, 0f));

        calibration._Calibrate();

        Assert.IsFalse(runtime.Store.ContainsKey(Key));
        Assert.IsTrue(label.text.Contains("level"), label.text);
    }

    [Test]
    public void Calibrate_RejectsAPileThatCannotShowTheRequiredChips()
    {
        PlaceLeftHand(Quaternion.identity);
        // A column holds at most stackHeight (10) chips, so 11 can never be satisfied.
        calibration.calibrationChips = 11;

        calibration._Calibrate();

        Assert.IsFalse(runtime.Store.ContainsKey(Key));
        Assert.IsTrue(label.text.Contains("unavailable"), label.text);
    }

    [Test]
    public void Restore_AppliesTheSavedOffsetToEveryPile()
    {
        runtime.SeedVector3(Key, new Vector3(0.02f, 0.14f, 0.08f));

        calibration.OnPlayerRestored(runtime.LocalPlayer);

        foreach (PhysicalRaisePile target in new[] { first, second })
            Assert.AreEqual(0f, (target._GetScaledHandOffset() - new Vector3(0.02f, 0.14f, 0.08f)).magnitude, 0.0001f);
        Assert.IsTrue(label.text.Contains("Current offset: (0.020, 0.140, 0.080)"), label.text);
    }

    [Test]
    public void Restore_WithoutASavedValueKeepsTheDefaults()
    {
        calibration.OnPlayerRestored(runtime.LocalPlayer);

        Assert.AreEqual(0f, (first._GetScaledHandOffset() - first.handOffset).magnitude, 0.0001f);
    }

    [Test]
    public void Restore_IgnoresImplausibleSavedValues()
    {
        runtime.SeedVector3(Key, new Vector3(0f, 7f, 0f));

        calibration.OnPlayerRestored(runtime.LocalPlayer);

        Assert.AreEqual(0f, (first._GetScaledHandOffset() - first.handOffset).magnitude, 0.0001f);
    }

    [Test]
    public void Restore_IgnoresOtherPlayers()
    {
        runtime.SeedVector3(Key, new Vector3(0.02f, 0.14f, 0.08f));

        calibration.OnPlayerRestored(VrcRuntimeFake.MakePlayer(9, "Other", false));

        Assert.AreEqual(0f, (first._GetScaledHandOffset() - first.handOffset).magnitude, 0.0001f);
    }

    [Test]
    public void Reset_RestoresTheDefaultOnEveryPileAndTheLabel()
    {
        PlaceLeftHand(Quaternion.identity);
        calibration._Calibrate();
        Assert.AreNotEqual(0f, (first._GetScaledHandOffset() - first.handOffset).magnitude);

        calibration._ResetToDefault();

        foreach (PhysicalRaisePile target in new[] { first, second })
            Assert.AreEqual(0f, (target._GetScaledHandOffset() - target.handOffset).magnitude, 0.0001f);
        Assert.IsTrue(label.text.Contains("Current offset: (0.000, 0.090, 0.050)"), label.text);
        Assert.IsTrue(label.text.Contains("Reset to default"), label.text);
    }

    [Test]
    public void Reset_StoresAMarkerThatRestoreIgnores()
    {
        PlaceLeftHand(Quaternion.identity);
        calibration._Calibrate();
        calibration._ResetToDefault();

        Assert.IsFalse(PhysicalRaiseSelectionMath.IsPlausibleOffset(Saved));

        calibration.OnPlayerRestored(runtime.LocalPlayer);
        Assert.AreEqual(0f, (first._GetScaledHandOffset() - first.handOffset).magnitude, 0.0001f);
    }

    [Test]
    public void Calibrate_AfterAResetWorksAgain()
    {
        PlaceLeftHand(Quaternion.identity);
        calibration._Calibrate();
        calibration._ResetToDefault();

        calibration._Calibrate();

        Assert.IsTrue(PhysicalRaiseSelectionMath.IsPlausibleOffset(Saved));
        Assert.IsTrue(label.text.Contains("Previous offset: (0.000, 0.090, 0.050)"), label.text);
    }
}
