<?php
namespace nur\io\json;

use IteratorAggregate;
use nur\A;
use nur\b\ICloseable;
use nur\b\io\IReader;
use nur\b\params\Parametrable;
use nur\b\params\Tparametrable;
use nur\reader;
use Symfony\Component\Yaml\Yaml;

/**
 * Class YamlReader
 *
 * --autogen-properties-and-methods--
 * @method setInput($value)
 */
class YamlReader extends Parametrable implements IteratorAggregate, ICloseable {
  use Tparametrable;

  function __construct($input=null, ?array $params=null) {
    A::set_nn($params, "input", $input);
    parent::__construct($params);
  }

  const PARAMETRABLE_PARAMS_SCHEMA = [
    "input" => [null, null, "fichier en entrée"],
  ];

  protected $ppInput;

  function pp_setInput($input): void {
    if ($input instanceof IReader) $this->reader = $input;
    else $this->ppInput = $input;
  }

  /** @var IReader */
  protected $reader;

  function getIterator() {
    $reader = $this->reader;
    if ($reader === null) $reader = $this->reader = reader::with($this->ppInput);

    try {
      $flags = Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE;
      yield Yaml::parse($reader->getContents(), $flags);
    } finally {
      $this->close();
    }
  }

  function close(): void {
    if ($this->reader !== null) {
      $this->reader->close();
      $this->reader = null;
    }
  }

  #############################################################################
  const _AUTOGEN_CONSTS = [
    "" => [self::class, "_autogen_consts", self::class],
  ];
  const _AUTOGEN_LITERALS = /*autogen*/[
    [
      \nur\b\params\parametrable_utils::class,
      '\\nur\\b\\params\\parametrable_utils::class',
    ],
    [self::class, 'self::class'],
    [
      self::PARAMETRABLE_PARAMS_SCHEMA,
      'self::PARAMETRABLE_PARAMS_SCHEMA',
    ],
  ];
  const _AUTOGEN_METHODS = /*autogen*/[
    [
      \nur\b\params\parametrable_utils::class,
      '_autogen_methods_getters',
      self::PARAMETRABLE_PARAMS_SCHEMA,
      self::class,
    ],
    [
      \nur\b\params\parametrable_utils::class,
      '_autogen_methods_setters',
      self::PARAMETRABLE_PARAMS_SCHEMA,
      self::class,
    ],
  ];
  const _AUTO_GETTERS = /*autogen*/[];
  const _AUTO_SETTERS = /*autogen*/[
    'setInput' => 'input',
  ];
  #--autogen-dynamic--
}
