using System.Reflection;
using common;
using eagle;
using NUnit.Framework;
using UnityEngine;

namespace eagle0.Tests {
    [TestFixture]
    public class PersistentUIManagerTests {
        [Test]
        public void RewiresStatusUiWhenCurrentConnectionIsReplaced() {
            var previousConnection = PersistentClientConnection.Current;
            var managerObject = new GameObject("PersistentUIManager test");
            var statusObject = new GameObject("ConnectionStatusUI test");
            try {
                var manager = managerObject.AddComponent<PersistentUIManager>();
                var statusUi = statusObject.AddComponent<ConnectionStatusUI>();
                manager.connectionStatusUI = statusUi;
                var firstConnection = new PersistentClientConnection(null, null, default);
                var replacementConnection = new PersistentClientConnection(null, null, default);

                PersistentClientConnection.Current = firstConnection;
                InvokeTryWireConnection(manager);
                Assert.AreSame(firstConnection, GetMonitoredConnection(statusUi));

                PersistentClientConnection.Current = replacementConnection;
                InvokeTryWireConnection(manager);
                Assert.AreSame(replacementConnection, GetMonitoredConnection(statusUi));
            } finally {
                PersistentClientConnection.Current = previousConnection;
                Object.DestroyImmediate(managerObject);
                Object.DestroyImmediate(statusObject);
            }
        }

        private static void InvokeTryWireConnection(PersistentUIManager manager) {
            var method = typeof(PersistentUIManager)
                                 .GetMethod(
                                         "TryWireConnection",
                                         BindingFlags.Instance | BindingFlags.NonPublic);
            Assert.NotNull(method);
            method.Invoke(manager, null);
        }

        private static PersistentClientConnection GetMonitoredConnection(
                ConnectionStatusUI statusUi) {
            var field = typeof(ConnectionStatusUI)
                                .GetField(
                                        "_connection",
                                        BindingFlags.Instance | BindingFlags.NonPublic);
            Assert.NotNull(field);
            return (PersistentClientConnection)field.GetValue(statusUi);
        }
    }
}
