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

use nulib\cl;
use nulib\ref\schema\ref_schema;
use nur\sery\wip\schema\Schema;
use nur\sery\wip\schema\Wrapper;

/**
 * Class AssocSchema
 */
class AssocSchema extends Schema {
  /** @var array meta-schema d'un schéma de nature tableau associatif */
  const METASCHEMA = ref_schema::ASSOC_METASCHEMA;

  /**
   * indiquer si $definition est une définition de schéma de nature tableau
   * associatif que {@link normalize()} pourrait normaliser
   */
  static function isa_definition($definition): bool {
    if (!is_array($definition)) return false;
    # nature explicitement spécifiée
    if (self::have_nature($definition, $nature)) {
      return $nature === "assoc";
    }
    # tableau associatif
    return !cl::have_num_keys($definition);
  }

  static function normalize($definition, $definitionKey=null): array {
    if (!is_array($definition)) $definition = [$definition];
    if (!self::have_nature($definition)) {
      $definition = [
        "?array",
        "" => "assoc",
        "schema" => $definition,
      ];
    }
    self::_normalize($definition, $definitionKey);
    self::_ensure_nature($definition, "assoc", "array");
    return $definition;
  }

  function __construct($definition=null, $definitionKey=null, bool $normalize=true) {
    if ($definition === null) $definition = static::SCHEMA;
    if ($normalize) {
      $definition = self::normalize($definition, $definitionKey);
      $this->_definition = $definition;
      self::_ensure_type($definition);
      self::_ensure_schema_instances($definition);
    }
    $this->definition = $definition;
  }

  function isAssoc(?AssocSchema &$schema=null): bool {
    $schema = $this;
    return true;
  }

  protected function newWrapper(): AssocWrapper {
    return new AssocWrapper($this);
  }

  function getWrapper(&$array=null, $arrayKey=null, ?Wrapper &$wrapper=null): AssocWrapper {
    if (!($wrapper instanceof AssocWrapper)) $wrapper = $this->newWrapper();
    return $wrapper->reset($array, $arrayKey);
  }
}
