<?php
namespace nur\data\types;

use nur\b\date\Date;

class SDateType extends RegexpType {
  const TITLE = "date";

  private static $instance;
  static final function to_date($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+0{1,2}[hH:.,]0{1,2}(?:[:.,]0{1,2})?)?/',
    '/^(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})(?:\s*00:00:00)?/',
    '/^(?<d>\d{2})(?<m>\d{2})(?<y>\d{2,4})?/',
  ];
  const PATTERN_NORMALIZED = Date::PATTERN;

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

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

  function formatDate(?string $date, string $format="Y-m-d"): ?string {
    if ($date === null) return null;
    return date($format, Date::parse_date($date));
  }
}
