<?php

/**
 * Helpers related to time.
 *
 * @package northmill-online-shared
 * @noinspection PhpUnused
 */
declare (strict_types=1);
namespace Northmill_Online_Shared_Checkout\Northmill_Online_Shared\Helpers;

use DateTime;
use DateTimeZone;
use Exception;
use Northmill_Online_Shared_Checkout\Northmill_Online_Shared\Abstract_Shared_Base;
use Northmill_Online_Shared_Checkout\Northmill_Online_Shared\Modules\Loggers\Log_Level_Enum;
use Throwable;
/**
 * Time helper functions.
 */
class Time_Helpers
{
    /**
     * Get timezone.
     *
     * @return DateTimeZone
     */
    public static function get_timezone(): DateTimeZone
    {
        static $zone = null;
        if (is_null($zone)) {
            $zone = new DateTimeZone('Europe/Stockholm');
        }
        return $zone;
    }
    /**
     * Gets current time using the same timezone as Apps
     *
     * @param string|null $format Format to return. If null, a DateTime object is returned.
     *
     * @return string|DateTime String if $format is set, else DateTime
     */
    public static function get_current_time(?string $format = null): DateTime|string
    {
        try {
            $date = new DateTime('now', self::get_timezone());
        } catch (Exception $e) {
            Abstract_Shared_Base::base_instance()->logger->log('helper', 'Failed to get current time', array('error' => $e), Log_Level_Enum::ERROR);
            return '';
        }
        return is_null($format) ? $date : $date->format($format);
    }
    /**
     * Get the current time in the format that the API expects.
     *
     * @return string Requested time.
     */
    public static function get_current_api_time(): string
    {
        return self::get_current_time('Y-m-d\TH:i:s');
    }
    /**
     * Creates DateTime object from Hub API timestamp.
     *
     * @param string $api_timestamp For example, 2021-03-01T14:24. It can also contain microseconds, which will be ignored.
     *
     * @return DateTime|false A DateTime object, false on error
     */
    public static function get_datetime_from_api_timestamp(string $api_timestamp): DateTime|false
    {
        return DateTime::createFromFormat('Y-m-d\TH:i:s', preg_replace('/\.\d*$/', '', $api_timestamp), self::get_timezone());
    }
    /**
     * Get age of a timestamp in a human-readable format.
     *
     * @param int $timestamp Timestamp to get age of.
     *
     * @return string
     */
    public static function get_timestamp_age(int $timestamp): string
    {
        $now = new DateTime();
        try {
            $then = new DateTime('@' . $timestamp);
            // '@' is used to pass a Unix timestamp to DateTime constructor
        } catch (Throwable) {
            return '';
        }
        $diff = $now->diff($then);
        if ($diff->y) {
            return $diff->y . ' ' . _n('year', 'years', $diff->y, 'northmill-online-shared');
        } elseif ($diff->m) {
            return $diff->m . ' ' . _n('month', 'months', $diff->m, 'northmill-online-shared');
        } elseif ($diff->d) {
            return $diff->d . ' ' . _n('day', 'days', $diff->d, 'northmill-online-shared');
        } elseif ($diff->h) {
            return $diff->h . ' ' . _n('hour', 'hours', $diff->h, 'northmill-online-shared');
        } elseif ($diff->i) {
            return $diff->i . ' ' . _n('minute', 'minutes', $diff->i, 'northmill-online-shared');
        } else {
            return $diff->s . ' ' . _n('second', 'seconds', $diff->s, 'northmill-online-shared');
        }
    }
    /**
     * Get a duration label.
     *
     * @param int $duration Duration in minutes.
     *
     * @return string Text intended for user to show duration
     */
    public static function get_duration_label(int $duration): string
    {
        if ($duration < 120) {
            return $duration . ' min';
        }
        $days = floor($duration / 1440);
        $hours = floor(($duration - $days * 1440) / 60);
        $minutes = $duration - $days * 24 * 60 - $hours * 60;
        $label = array();
        if ($days > 0) {
            $label[] = sprintf(
                // translators: %d is the number of days.
                _n('%d day', '%d days', $days, 'northmill-online-shared'),
                $days
            );
        }
        if ($hours > 0) {
            $label[] = sprintf(
                // translators: %d is the number of hours.
                _n('%d hour', '%d hours', $hours, 'northmill-online-shared'),
                $hours
            );
        }
        if ($minutes > 0) {
            $label[] = sprintf(
                // translators: %d is the number of minutes.
                _n('%d minute', '%d minutes', $minutes, 'northmill-online-shared'),
                $minutes
            );
        }
        return implode(' ', $label);
    }
}
