<?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 tfloat extends _tformatable {
  const NAME = "float";

  const ALIASES = ["flt", "double", "dbl"];

  static function ensure_float(&$float): void {
    if (!is_float($float)) $float = floatval($float);
  }

  static function ensure_nfloat(&$float): void {
    if ($float !== null) self::ensure_float($float);
  }

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

  function isValid($value, ?bool &$normalized=null): bool {
    $normalized = is_float($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 floatval($value);
    throw new ValueException("une valeur numérique flottante est attendue");
  }

  /**
   * @var ScalarResult $result
   * @var ScalarSchema $schema
   */
  function verifix(&$value, Result $result, Schema $schema): bool {
    if (is_float($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 = floatval($value);
      $result->setValid();
      return true;
    }
    $result->setInvalid($value, $schema);
    return false;
  }
}
