using MrEModuleSdk.Devices.Mre3;
using System;

namespace Mre3Example
{
    public partial class Mre3Example
    {
        static void Main()
        {
            // MrE3SdkComDeviceController is the main customer entry point for MR-E-3 devices.
            var controller = new MrE3SdkComDeviceController();

            try
            {
                PrintWelcome();

                var port = PromptForComPort();
                if (!port.HasValue)
                {
                    Console.WriteLine("Invalid COM port number.");
                    return;
                }

                if (!controller.Connect(port.Value))
                {
                    throw new InvalidOperationException("Connection failed.");
                }

                Console.WriteLine("Connection successful.");
                Console.WriteLine();

                PrintConnectedDeviceSummary(controller);

                while (true)
                {
                    PrintMenu();
                    var selection = Console.ReadLine();

                    if (string.Equals(selection, "0", StringComparison.OrdinalIgnoreCase) ||
                        string.Equals(selection, "q", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine("Closing MR-E-3 examples.");
                        break;
                    }

                    RunSelectedExample(controller, selection);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Example failed: {ex.Message}");
            }
            finally
            {
                StopDynamicSources(controller);
                controller.Disconnect(true);
                Console.WriteLine();
                Console.WriteLine("Example finished. Press Enter to close.");
                Console.ReadLine();
            }
        }

        private static void RunSelectedExample(IMrE3SdkComDeviceController controller, string selection)
        {
            Console.WriteLine();

            switch (selection)
            {
                case "1":
                    RunDeviceOverviewExample(controller);
                    break;
                case "2":
                    RunStaticInputExample(controller);
                    break;
                case "3":
                    RunSignalGeneratorExample(controller);
                    break;
                case "4":
                    RunReadoutValuesExample(controller);
                    break;
                case "5":
                    RunOperationModesExample(controller);
                    break;
                case "6":
                    RunVectorPatternTriggerExample(controller);
                    break;
                default:
                    Console.WriteLine("Unknown option. Please choose a value from the menu.");
                    break;
            }

            Console.WriteLine();
        }
    }
}
