<?php
declare(strict_types=1);

namespace App\Service\Utils;

use DateTime;
use DateTimeInterface;
use DateTimeZone;
use Exception;

/**
 * Class Dates : méthodes d'aide pour la gestion de dates.
 * @package App\Service\Utils
 */
class DatesUtils
{
    // For testing purpose, see setFakeDatetime and clearFakeDatetime method
    protected static string | null $fakeDateTime = null;

    /**
     * @throws Exception
     */
    public static function new(string $datetime = "now", ?DateTimeZone $timezone = null): DateTime
    {
        if ($datetime === 'now') {
            $datetime = static::$fakeDateTime ?? $datetime;
        }
        return new DateTime($datetime, $timezone);
    }

    /**
     * Set a fake datetime string that will be use in the 'new' method instead of whenever
     * the passed datetime is 'now'
     *
     *
     * @param string $datetime
     */
    public static function setFakeDatetime(string $datetime): void
    {
        self::$fakeDateTime = $datetime;
    }

    public static function clearFakeDatetime(): void
    {
        self::$fakeDateTime = null;
    }

    /**
     * Vérifie si la date du jour est comprise dans l'interval passé en paramètres
     * @param DateTimeInterface $dateStart
     * @param DateTimeInterface|null $dateEnd
     * @return bool
     * @see DatesUtilsTest::testIsIntervalIsValidNow()
     */
    public static function isIntervalIsValidNow(DateTimeInterface $dateStart, DateTimeInterface $dateEnd = null): bool
    {
        $now = new DateTime('now');
        return $dateStart <= $now && (is_null($dateEnd) || $dateEnd >= $now);
    }
}
