<?php
namespace nur\sery\wip\schema\types;

use nulib\ValueException;
use nur\sery\wip\schema\_scalar\ScalarResult;
use nur\sery\wip\schema\_scalar\ScalarSchema;
use nur\sery\wip\schema\Result;
use nur\sery\wip\schema\Schema;

class tint extends _tformatable {
  const NAME = "int";

  const ALIASES = ["integer"];

  static function ensure_int(&$int): void {
    if (!is_int($int)) $int = intval($int);
  }

  static function ensure_nint(&$int): void {
    if ($int !== null) self::ensure_int($int);
  }

  //const INT_PATTERN = '/^[-+]?[0-9]+(?:\.[0-9]*)?$/';

  function getClass(): string {
    return "int";
  }

  function isValid($value, ?bool &$normalized=null): bool {
    $normalized = is_int($value);
    return is_scalar($value);
  }

  function extract(string $value): string {
    return trim($value);
  }

  function parse(string $value) {
    $value = str_replace(",", ".", trim($value));
    if (is_numeric($value)) return intval($value);
    throw new ValueException("une valeur numérique entière est attendue");
  }

  /**
   * @var ScalarResult $result
   * @var ScalarSchema $schema
   */
  function verifix(&$value, Result $result, Schema $schema): bool {
    if (is_int($value)) {
      $result->setNormalized();
      return false;
    } elseif (is_string($value)) {
      try {
        $value = $this->parse($value);
        $result->setValid();
        return true;
      } catch (ValueException $e) {
      }
    } elseif (is_scalar($value)) {
      $value = intval($value);
      $result->setValid();
      return true;
    }
    $result->setInvalid($value, $schema);
    return false;
  }
}
