using System;
using System.Collections.Generic;
using System.Linq;
using Interfaces;
using RaceLapTimer.Assists;

namespace RaceLapTimer.Extensions.TransponderUtilities
{
    class TransponderUtilityManager : ITransponderUtilityManager
    {
        private List<ITransponderUtilityProvider> _providers;
        private readonly ILoggerService _logger;

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

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

        public List<ITransponderUtilityProvider> GetProviders()
        {
            return _providers;
        }

        public int GetLastScannedId()
        {
            //TODO: Implement a utlity provider selector, this can only work with one transponder utility provider.
            if (_providers.Any())
            {
                var provider = _providers.First();
                var lastId = AsyncHelpers.RunSync(_providers.First().GetLastScannedIdAsync);
                _logger.Trace("Got Id {0} from provider {1}", lastId, provider.GetType().Name);
                return lastId;
            }
            return -1;
        }
    }
}
