using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KarleyLibrary.Erweiterungen
{
    public static class DateTimeErweiterung
    {
        public static string RelativeZeit(DateTime yourDate)
        {
            const int SECOND = 1;
            const int MINUTE = 60 * SECOND;
            const int HOUR = 60 * MINUTE;

            var ts = new TimeSpan(DateTime.Now.Ticks - yourDate.Ticks);
            double delta = Math.Abs(ts.TotalSeconds);

            if (delta < 1 * MINUTE)
            {
                return ts.Seconds == 1 ? "vor einer Sekunde" : "vor " + ts.Seconds + " Sekunden";
            }

            if (delta < 2 * MINUTE)
            {
                return "vor einer Minute";
            }

            if (delta < 45 * MINUTE)
            {
                return "vor " + ts.Minutes + " Minuten";
            }

            if (delta < 120 * MINUTE)
            {
                return "vor einer Stunde";
            }

            if (delta < 24 * HOUR)
            {
                return "vor " + ts.Hours + " Stunden";
            }

            if (delta < 48 * HOUR)
            {
                return "gestern";
            }

            return DateTime.Now.ToString("dd. MMMM yyyy");
        }

        public static DateTime NächstesDatumWochentag(DateTime datum, bool descending)
        {
            DateTime tmpDatum = datum;
            HolidayDays holiday = new HolidayDays();

            while (holiday.IsHoliday(tmpDatum, State.NordrheinWestfalen) || tmpDatum.DayOfWeek is DayOfWeek.Saturday || tmpDatum.DayOfWeek is DayOfWeek.Sunday)
            {
                tmpDatum = tmpDatum.AddDays(descending ? -1 : 1);
            }

            return tmpDatum;
        }

        public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
        {
            int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
            return dt.AddDays(-1 * diff).Date;
        }

        public static DateTime EndOfWeek(this DateTime dt, DayOfWeek endOfWeek)
        {
            return StartOfWeek(dt, (DayOfWeek)(((int)endOfWeek + 1) % 7)).AddDays(6).Date;
        }
    }
}
