<?php
namespace nur;

use nur\data\types\IType;
use nur\data\types\PhpIncarnation;

/**
 * Class types: gestion de types de valeurs
 */
class types {
  const MANAGER_CLASS = PhpIncarnation::class;

  protected static $manager_class;

  /**
   * spécifier la classe à utiliser pour instancier le gestionnaire
   * de types
   *
   * cette méthode *doit* être appelée avant d'appeler la méthode
   * {@link manager()}
   */
  static final function set_manager_class(string $manager_class) {
    self::$manager_class = $manager_class;
  }

  /** @var PhpIncarnation */
  protected static $manager;

  static final function set_manager(PhpIncarnation $manager) {
    self::$manager = $manager;
  }

  /** obtenir l'instance globale de gestionnaire de types */
  static final function manager(): PhpIncarnation {
    if (self::$manager === null) {
      $manager_class = self::$manager_class;
      if ($manager_class === null) $manager_class = static::MANAGER_CLASS;
      self::$manager = new $manager_class();
    }
    return self::$manager;
  }

  static final function __callStatic($name, $args) {
    $name = str::us2camel($name);
    return call_user_func_array([self::$manager, $name], $args);
  }

  #############################################################################

  static final function get($name, bool $required=true): ?IType { return self::manager()->getType($name, $required); }
  static final function add($typeOrClass, ?string $name=null): void { self::manager()->addType($typeOrClass, $name); }
  static final function is_instance($type, $value): bool { return self::manager()->getType($type)->isInstance($value); }
  static final function can_format($type): bool { return self::manager()->getType($type)->canFormat(); }
  static final function format($type, $value): string { return self::manager()->getType($type)->format($value); }
  static final function can_parse($type): bool { return self::manager()->getType($type)->canParse(); }
  static final function parse($type, string &$input) { return self::manager()->getType($type)->parse($input); }
  static final function verifix($type, &$value, array &$result=null, bool $throw=false): bool { return self::manager()->getType($type)->verifix($value, $result, $throw); }
  static final function with($type, $value) { return self::manager()->getType($type)->with($value); }
}