<?php
namespace nur\b\date;

use nur\b\ValueException;

class Date extends Datetime {
  const PATTERN = '/^(\d{2})\/(\d{2})\/(\d{4})$/';
  const FORMAT = "d/m/Y";

  static function parse_date($date): int {
    if ($date instanceof Datetime) {
      $date = $date->getTime();
    } elseif ($date === null || is_int($date)) {
      if ($date === null) $date = time();
    } elseif (is_array($date)) {
      [$y, $m, $d] = $date;
      $date = mktime(0, 0, 0, $m, $d, $y);
    } elseif (is_string($date) && preg_match(self::PATTERN, $date, $ms)) {
      $d = intval($ms[1]);
      $m = intval($ms[2]);
      $y = intval($ms[3]);
      $date = mktime(0, 0, 0, $m, $d, $y);
    } else {
      throw ValueException::invalid_value($date, "date");
    }
    return $date;
  }

  function __construct($date=null) {
    parent::__construct(false);
    if ($date !== false) {
      $this->setTime(self::parse_date($date));
    }
  }

  protected function afterUpdate(): void {
    $this->wrapStart();
  }
}