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

namespace BoFilTest.Domain.Modules
{
    class YoctupuceCapability
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        private static int referenceCount = 0;

        public static void Acquire()
        {
            if (referenceCount == 0)
            {
                Start();
            }
            referenceCount++;
            logger.Info("Incremented Yoctupuce users to {0}", referenceCount);
        }

        public static void Release()
        {
            referenceCount--;
            logger.Info("Decremented Yoctopuce users to {0}", referenceCount);
            if (referenceCount == 0)
            {
                Stop();
            }
        }

        private static void Start()
        { 
            logger.Info("Starting Yoctopuce hub");

            string Message = "";
            if (YAPI.RegisterHub("usb", ref Message) != YAPI.SUCCESS)
            {
                throw new HardwareException("Unable to initialize Yocto API: " + Message);
            }

            if (YAPI.UpdateDeviceList(ref Message) != YAPI.SUCCESS)
            {
                throw new HardwareException("Unable to get device list: " + Message);
            }
        }

        private static void Stop()
        {
            YAPI.UnregisterHub("usb");
            logger.Info("Stopping Yoctopuce hub.");
        }
       
    }
}
