Source

TrafficLight / src / Core / Services / ProjectMonitorService.cs

Full commit
using System;
using System.Linq;
using RossCode.TrafficLight.Core.Domain;
using RossCode.TrafficLight.Core.Domain.Repositories;
using RossCode.TrafficLight.Core.Eventing;
using RossCode.TrafficLight.Core.Eventing.Events;
using RossCode.TrafficLight.Core.Utilities;

namespace RossCode.TrafficLight.Core.Services
{
    public interface IProjectMonitorService
    {
        void StartMonitoring();
    }

    public class ProjectMonitorService : IProjectMonitorService
    {
        private readonly IProjectRepository projectRepository;
        private readonly IProjectService projectService;
        private readonly ITimer timer;

        public ProjectMonitorService(IProjectRepository projectRepository, IProjectService projectService, ITimer timer)
        {
            this.projectRepository = projectRepository;
            this.projectService = projectService;
            this.timer = timer;
        }

        public void StartMonitoring() 
        {
            var projects = projectRepository.GetAll().ToList();
            if (!projects.Any())
            {
                DomainEvents.Raise(new EditProjectRequested(new Project()));
            }
            projectService.CheckAndSetStatusesFor(projects);

            timer.TimerElapsed += (sender, args) => TimerElapsed();
            timer.IntervalInSeconds = 60;
            timer.Start();

            DomainEvents.Register<ProjectAdded>(args => TimerElapsed());
        }

        private void TimerElapsed()
        {
            timer.Stop();
            projectService.CheckAndSetStatusesFor(projectRepository.GetAll().ToList());
            timer.Start();
        }
    }
}