using System;
using System.Diagnostics;
using System.Threading;
using TrajectoryPlanningVisualization;

namespace TrajectoryPlanningVisualizationVerificationHost;

internal static class Program
{
    private static int Main(string[] args)
    {
        if (args.Length == 2 && args[0] == "--smoke-seconds" &&
            int.TryParse(args[1], out int seconds) && seconds > 0)
        {
            return RunSmoke(seconds);
        }

        try
        {
            ContractChecks.Run();
            RuntimeChecks.Run();
            ServerChecks.Run();
            WebAssetChecks.Run();
            Console.WriteLine("PASS trajectory-planning-visualization");
            return 0;
        }
        catch (Exception exception)
        {
            Console.Error.WriteLine(exception);
            return 1;
        }
    }

    private static int RunSmoke(int seconds)
    {
        try
        {
            using var session = new PlanningVisualizationSession(
                new PlanningVisualizationOptions { Port = 0, RefreshRateHz = 10, HistoryCycleLimit = 60 });
            PlanningVisualizationSessionInfo info = session.Start(SampleSnapshotFactory.CreateStaticSnapshot());
            Console.WriteLine(info.Uri.AbsoluteUri);
            Stopwatch stopwatch = Stopwatch.StartNew();
            long sequence = 1L;
            while (stopwatch.Elapsed < TimeSpan.FromSeconds(seconds))
            {
                session.Publish(SampleSnapshotFactory.CreateDynamicSnapshot(sequence++));
                TimeSpan remaining = TimeSpan.FromSeconds(seconds) - stopwatch.Elapsed;
                if (remaining <= TimeSpan.Zero)
                {
                    break;
                }

                Thread.Sleep(remaining < TimeSpan.FromMilliseconds(100) ? remaining : TimeSpan.FromMilliseconds(100));
            }

            session.Stop();
            return 0;
        }
        catch (Exception exception)
        {
            Console.Error.WriteLine(exception);
            return 1;
        }
    }
}
