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

use nur\sery\ref\schema\ref_schema;
use nur\sery\wip\schema\Schema;
use nur\sery\wip\schema\Value;

class ListSchema extends Schema {
  /** @var array meta-schema d'un schéma de nature liste */
  const METASCHEMA = ref_schema::LIST_METASCHEMA;

  /**
   * indiquer si $definition est une définition de schéma de nature liste que
   * {@link normalize()} pourrait normaliser
   */
  static function isa_definition($definition): bool {
    if (!is_array($definition)) return false;
    # nature explicitement spécifiée
    if (array_key_exists("", $definition)) {
      $nature = $definition[""];
      if ($nature === "list") return true;
      if (is_array($nature)
        && array_key_exists(0, $nature)
        && $nature[0] === "list") {
        return true;
      }
      return false;
    }
    # un unique élément tableau à l'index 0
    $count = count($definition);
    $haveIndex0 = array_key_exists(0, $definition);
    return $count == 1 && $haveIndex0 && is_array($definition[0]);
  }

  static function normalize($definition, $definitionKey=null): array {
  }

  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;
  }

  function isList(?ListSchema &$list=null): bool {
    $list = $this;
    return true;
  }

  function newValue(?Value &$destv=null, &$dest=null, $destKey=null): ListValue {
    if ($destv instanceof ListValue) return $destv->reset($dest, $destKey);
    else return ($destv = new ListValue($this, $dest, $destKey));
  }
}
