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

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 tpkey extends _tunion {
  const NAME = "pkey";

  static function ensure_pkey(&$pkey): void {
    if ($pkey === null) $pkey = "";
    elseif ($pkey === false) $pkey = 0;
    elseif (!is_string($pkey) && !is_int($pkey) && !is_array($pkey)) $pkey = strval($pkey);
    if (is_array($pkey)) {
      foreach ($pkey as &$key) {
        tkey::ensure_key($key);
      }; unset($key);
    }
  }

  static function ensure_npkey(&$pkey): void {
    if ($pkey !== null) self::ensure_pkey($pkey);
  }

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

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

  function parse(string $value) {
    return $value;
  }

  /**
   * @var ScalarResult $result
   * @var ScalarSchema $schema
   */
  function verifix(&$value, Result $result, Schema $schema): bool {
    if (is_string($value) || is_int($value) || is_array($value)) {
      $result->setNormalized();
      return false;
    } elseif (is_scalar($value)) {
      $value = strval($value);
      $result->setValid();
      return true;
    } else {
      $result->setInvalid($value, $schema);
      return false;
    }
  }

  function format($value, $format=null): string {
    if (is_array($value)) return implode(".", $value);
    else return strval($value);
  }
}
