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

namespace RaceLapTimer.Extensions.Notifications
{
    class NotificationManager : INotifierManager
    {
        private List<INotifierProvider> _providers;

        public NotificationManager(IPluginLocator locator)
        {
            RegisterProviders(locator);
        }

        private void RegisterProviders(IPluginLocator locator)
        {
            var providerFactories = locator.Locate<INotifierProviderFactory>();
            _providers = new List<INotifierProvider>();
            foreach (var factory in providerFactories)
            {
                _providers.Add(factory.GetProvider());
            }
        }

        public List<string> GetAvailableNotifiers()
        {
            return _providers.Select(provider => provider.GetDisplayName()).ToList();
        }

        public void NotifyRaceStarted(NotificationEventArgs args)
        {
            try
            {
                foreach (var provider in _providers)
                {
                    Task.Factory.StartNew(() => { provider.NotifyRaceStarted(args); });
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }

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

        public void NotifyRaceLapEvent(NotificationEventArgs args, Pilot pilot)
        {
            foreach (var provider in _providers)
            {
                Task.Factory.StartNew(() => provider.NotifyRaceLapEvent(args, pilot));
            }
        }

        public void NotifyRaceWinner(NotificationEventArgs args, Pilot pilot)
        {
            foreach (var provider in _providers)
            {
                Task.Factory.StartNew(() => provider.NotifyRaceWinner(args, pilot));
            }
        }

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