<?php
namespace nur\data\types;

use nur\b\date\Date;
use nur\b\date\Datetime;

class SDatetimeType extends RegexpType {
  const TITLE = "date et heure";

  private static $instance;
  static final function to_datetime($value) {
    $type = self::$instance;
    if ($type === null) self::$instance = $type = new self();
    return $type->with($value);
  }

  const PATTERN = [
    '/^(?<d>\d{1,2})[-\/]+(?<m>\d{1,2})(?:[-\/]+(?<y>\d{2,4}))?\s+(?<H>[0-9]{1,2})[hH:.,](?<M>[0-9]{1,2})(?:[:.,](?<S>[0-9]{1,2}))?/',
    '/^(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2}) (?<H>\d{2}):(?<M>\d{2}):(?<S>\d{2})/',
    '/^(?<d>\d{2})(?<m>\d{2})(?<y>\d{2,4})?\s+(?<H>[0-9]{1,2})[hH:.,](?<M>[0-9]{1,2})(?:[:.,](?<S>[0-9]{1,2}))?/',
    '/^(?<d>\d{1,2})[-\/]+(?<m>\d{1,2})(?:[-\/]+(?<y>\d{2,4}))?/',
    '/^(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/',
    '/^(?<d>\d{2})(?<m>\d{2})(?<y>\d{2,4})?/',
  ];
  const PATTERN_NORMALIZED = Datetime::PATTERN;

  /** @return array un tableau de la forme [$y, $m, $d, $H, $M, $S] */
  protected function extractParsedValue(array $ms) {
    $d = intval($ms["d"]);
    $m = intval($ms["m"]);
    $y = isset($ms["y"]) && $ms["y"]? intval($ms["y"]): null;
    if ($y === null) $y = intval(date("Y"));
    else $y = Date::fix_any_year($y);
    $H = isset($ms["H"])? intval($ms["H"]): 0;
    $M = isset($ms["M"])? intval($ms["M"]): 0;
    $S = isset($ms["S"])? intval($ms["S"]): 0;
    return [$y, $m, $d, $H, $M, $S];
  }

  function verifixConvert(&$value): bool {
    if ($value === null) return true;
    $value = (new Datetime($value))->format();
    return true;
  }

  function formatDatetime(?string $datetime, string $format="Y-m-d H:i:s"): ?string {
    if ($datetime === null) return null;
    return date($format, Datetime::parse_datetime($datetime));
  }
}
