using System;

namespace InABox.Core
{
    public static class DateTimeExtensions
    {
        public static DateTime Floor(this DateTime dateTime, TimeSpan interval)
        {
            return dateTime.AddTicks(-(dateTime.Ticks % interval.Ticks));
        }

        public static TimeSpan Floor(this TimeSpan timespan, TimeSpan interval)
        {
            return timespan.Subtract(new TimeSpan(timespan.Ticks % interval.Ticks));
        }

        public static DateTime Ceiling(this DateTime dateTime, TimeSpan interval)
        {
            var overflow = dateTime.Ticks % interval.Ticks;

            return overflow == 0 ? dateTime : dateTime.AddTicks(interval.Ticks - overflow);
        }

        public static TimeSpan Ceiling(this TimeSpan timespan, TimeSpan interval)
        {
            var overflow = timespan.Ticks % interval.Ticks;

            return overflow == 0 ? timespan : timespan.Add(new TimeSpan(interval.Ticks - overflow));
        }


        public static DateTime Round(this DateTime dateTime, TimeSpan interval)
        {
            var halfIntervalTicks = (interval.Ticks + 1) >> 1;

            return dateTime.AddTicks(halfIntervalTicks - (dateTime.Ticks + halfIntervalTicks) % interval.Ticks);
        }

        public static TimeSpan Round(this TimeSpan timespan, TimeSpan interval)
        {
            var halfIntervalTicks = (interval.Ticks + 1) >> 1;

            return timespan.Add(new TimeSpan(halfIntervalTicks - (timespan.Ticks + halfIntervalTicks) % interval.Ticks));
        }
    }
}