using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

using Acroname.BrainStem2CLI;

namespace BrainStem2CLI_LED_Toggle
{
    class Program
    {
        static void Main(string[] args)
        {
            aErr err = aErr.aErrNone;

            Console.WriteLine("Creating a USBStem module");
            USBStem stem = new USBStem();

            //Returns with device information from the FIRST BrainStem device it finds.
            m_linkSpec spec = ModuleClass.findFirstModule(m_linkType.USB);

            if(spec.serial_num != 0) {
                //Most of the other examples use discoverAndConnect. This is typically the easiest
                //method; however, it requires that the Object (USBStem in this case) match the 
                //type of devices you are connecting to.
                //i.e. If you have a USBHub3p and discoverAndConnect is used from a USBHub2x4 object 
                //     it will NOT successfully connect. Returning aErr.aErrNotFound.
                //connectFromSpec does not have this restriction; which allows us to create
                //a generic example that works on ALL devices without modification.
                stem.module.connectFromSpec(spec);
                if(err != aErr.aErrNone) {
                    Console.WriteLine("Error connecting to device: {0}", err);
                    Console.WriteLine("Press enter to exit");
                    Console.ReadLine();
                    System.Environment.Exit(1);
                }
                else {
                    Console.WriteLine("Successfully connected to Device. SN: {0}", spec.serial_num);
                }
            }
            else {
                Console.WriteLine("Could not find and BrainStem devices.");
                Console.WriteLine("Press enter to exit");
                Console.ReadLine();
                System.Environment.Exit(1);
            }

            Console.WriteLine("Toggling the User LED on and off");
            for(int x = 0; x < 10; x++) {
                if(x % 2 == 0)  { stem.system.setLED(1); }
                else            { stem.system.setLED(0); }
                Thread.Sleep(1000);
            }

            Console.WriteLine("Disconnecting from device.");
            stem.module.disconnect();

            Console.WriteLine("Press enter to exit");
            Console.ReadLine();

        }
    }
}
