using System;
using System.Collections.Generic;
using System.Linq;

namespace Library
{
    public class Calculations
    {
        public string[] AvailablePeriods(
            TimeSpan[] startTimes, 
            int[] durations, 
            TimeSpan beginWorkingTime, 
            TimeSpan endWorkingTime, 
            int consultationTime)
        {
            var busyPeriods = new List<(TimeSpan Start, TimeSpan End)>();
            
            for (int i = 0; i < startTimes.Length; i++)
            {
                busyPeriods.Add((startTimes[i], startTimes[i].Add(TimeSpan.FromMinutes(durations[i]))));
            }
            
            busyPeriods = busyPeriods.OrderBy(p => p.Start).ToList();
            
            var result = new List<string>();
            TimeSpan current = beginWorkingTime;
            
            foreach (var busy in busyPeriods)
            {
                if (busy.Start > current)
                {
                    AddAvailablePeriods(current, busy.Start, consultationTime, result);
                }
                current = busy.End > current ? busy.End : current;
            }
            
            if (current < endWorkingTime)
            {
                AddAvailablePeriods(current, endWorkingTime, consultationTime, result);
            }
            
            return result.ToArray();
        }
        
        private void AddAvailablePeriods(TimeSpan start, TimeSpan end, int duration, List<string> result)
        {
            TimeSpan current = start;
            while (current.Add(TimeSpan.FromMinutes(duration)) <= end)
            {
                var next = current.Add(TimeSpan.FromMinutes(duration));
                result.Add($"{current:hh\\:mm}-{next:hh\\:mm}");
                current = next;
            }
        }
    }
}