Source

TrafficLight / src / Core / Services / Indicators / BuildIndicatorService.cs

using System.Collections.Generic;
using RossCode.TrafficLight.Core.Domain;
using RossCode.TrafficLight.Core.Domain.Repositories;
using RossCode.TrafficLight.Core.Eventing;
using RossCode.TrafficLight.Core.Eventing.Events;

namespace RossCode.TrafficLight.Core.Services.Indicators
{
    public interface IBuildIndicatorService
    {
        void StartIndicators(BuildStatus currentStatus = BuildStatus.Unknown);
        void ShutDownIndicators();
    }

    public class BuildIndicatorService : IBuildIndicatorService
    {
        private readonly IIndicatorTypeRepository indicatorTypeRepository;
        private readonly IList<IBuildStatusIndicatorService> services = new List<IBuildStatusIndicatorService>();
        private BuildStatus currentBuildStatus = BuildStatus.Unknown;

        public BuildIndicatorService(IIndicatorTypeRepository indicatorTypeRepository)
        {
            this.indicatorTypeRepository = indicatorTypeRepository;
            DomainEvents.Register<IndicatorsChanged>(IndicatorsChanged);
            DomainEvents.Register<BuildStatusChanged>(BuildStatusChanged);
            DomainEvents.Register<ShutDownRequested>(suspended => ShutDownIndicators());
        }

        private void BuildStatusChanged(BuildStatusChanged args)
        {
            currentBuildStatus = args.Status;
        }

        private void IndicatorsChanged(IndicatorsChanged args)
        {
            ShutDownIndicators();
            StartIndicators(currentBuildStatus);
        }

        public void StartIndicators(BuildStatus currentStatus = BuildStatus.Unknown)
        {
            services.Clear();
            var indicatorTypes = indicatorTypeRepository.GetAll();

            foreach (var indicatorType in indicatorTypes)
            {
                services.Add(IndicatorTypeMaps.GetIndicatorServiceFor[indicatorType]());
            }
            foreach (var service in services)
            {
                service.Start(currentStatus);
            }
        }

        public void ShutDownIndicators()
        {
            foreach (var service in services)
            {
                service.Stop();
            }
        }
    }
}