<?php
namespace nur\sery\php\time;

use InvalidArgumentException;

class DateInterval extends \DateInterval {
  static function with($interval): self {
    if ($interval instanceof static) return $interval;
    else return new static($interval);
  }

  protected static function to_string(DateInterval $interval) {
    $string = "P";
    $y = $interval->y;
    $m = $interval->m;
    $d = $interval->d;
    if ($y > 0) $string .= "${y}Y";
    if ($m > 0) $string .= "${m}M";
    if ($d > 0) $string .= "${d}D";
    $string .= "T";
    $h = $interval->h;
    $i = $interval->i;
    $s = $interval->s;
    if ($h > 0) $string .= "${h}H";
    if ($i > 0) $string .= "${i}M";
    if ($s > 0 || $string == "PT") $string .= "${s}S";
    if ($interval->invert == 1) $string = "-$string";
    return $string;
  }

  function __construct($duration) {
    if (is_int($duration)) $duration = "PT${duration}S";
    if ($duration instanceof \DateInterval) {
      $this->y = $duration->y;
      $this->m = $duration->m;
      $this->d = $duration->d;
      $this->h = $duration->h;
      $this->i = $duration->i;
      $this->s = $duration->s;
      $this->invert = $duration->invert;
      $this->days = $duration->days;
    } elseif (!is_string($duration)) {
      throw new InvalidArgumentException("duration must be a string");
    } else {
      if (substr($duration, 0, 1) == "-") {
        $duration = substr($duration, 1);
        $invert = true;
      } else {
        $invert = false;
      }
      parent::__construct($duration);
      if ($invert) $this->invert = 1;
    }
  }

  function __toString(): string {
    return self::to_string($this);
  }
}
