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

namespace RaceLapTimer.Extensions.SystemControl
{
    class SystemControlManager : ISystemControlManager
    {
        private List<ISystemControlProvider> _providers;
        private readonly ILoggerService _logger;

        public SystemControlManager(IPluginLocator locator, ILoggerService logger)
        {
            RegisterProviders(locator);
            _logger = logger;
        }

        private void RegisterProviders(IPluginLocator locator)
        {
            try
            {
                var providerFactories = locator.Locate<ISystemControlProviderFactory>();
                _providers = new List<ISystemControlProvider>();
                foreach (var factory in providerFactories)
                {
                    _providers.Add(factory.GetProvider());
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
        }

        public List<string> GetAvailableProviders()
        {
            return _providers.Select(x=>x.GetType().ToString()).ToList();
        }

        public void Shutdown()
        {
            foreach (var provider in _providers)
            {
                Task.Factory.StartNew(() => provider.Shutdown());
            }
        }
    }
}
