using Elwig.Helpers.Weighing;

namespace Tests.WeighingTests {
    [TestFixture]
    public class ScaleTestBadenL320 {

        private EventMockScale? Mock;
        private AveryEventScale? Scale;

        private static (string, bool) ScaleHandler(int weight, string? error, int identNr) {
            var modes = error?.Split(';') ?? [];
            var invalid = modes.Contains("invalid");
            var unit = modes.Contains("unit");

            if (invalid) {
                return ("abcd\r\n", false);
            }

            bool incr = true;
            return ($" {new DateTime(2020, 9, 28, 9, 8, 0):dd.MM.yy HH:mm} {identNr,4} {weight,9}{(unit ? "lb" : "kg")} \r\n", incr);
        }

        [OneTimeSetUp]
        public void SetupScale() {
            Mock = new EventMockScale(12345, ScaleHandler);
            Scale = new("1", "L320", "tcp://127.0.0.1:12345");
        }

        [OneTimeTearDown]
        public void TeardownScale() {
            Mock?.Dispose();
            Scale?.Dispose();
        }

        [SetUp]
        public void ResetScale() {
            Mock!.IdentNr = 0;
            Mock!.Weight = 0;
            Mock!.Error = null;
        }

        [Test]
        public async Task Test_01_Normal() {
            WeighingResult? res = null;
            Scale!.WeighingEvent += (sender, evt) => {
                res = evt.Result;
            };

            await Mock!.Weigh(2345);
            await Task.Delay(100);
            Assert.That(res, Is.Not.Null);
            Assert.That(res, Is.EqualTo(new WeighingResult {
                Weight = 2345, WeighingId = "1",
                FullWeighingId = $"2020-09-28/1",
                Date = new DateOnly(2020, 9, 28), Time = new TimeOnly(9, 8),
            }));

            await Mock!.Weigh(4215);
            await Task.Delay(100);
            Assert.That(res, Is.Not.Null);
            Assert.That(res, Is.EqualTo(new WeighingResult {
                Weight = 4215,
                WeighingId = "2",
                FullWeighingId = $"2020-09-28/2",
                Date = new DateOnly(2020, 9, 28),
                Time = new TimeOnly(9, 8),
            }));
        }
    }
}