<?php
namespace nur\io\json;

use IteratorAggregate;
use nur\A;
use nur\b\ICloseable;
use nur\b\io\EOFException;
use nur\b\io\IReader;
use nur\b\params\Parametrable;
use nur\b\params\Tparametrable;
use nur\reader;

/**
 * Class JsonReader
 *
 * --autogen-properties-and-methods--
 * @method bool isParseWhole()
 * @method setInput($value)
 * @method bool setParseWhole(bool $value)
 */
class JsonReader 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"],
    "parse_whole" => ["bool", false, "faut-il analyser le fichier en une seule fois au lieu de 'un objet par ligne'"],
  ];

  protected $ppInput;

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

  /** @var bool */
  protected $ppParseWhole;

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

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

    try {
      $flags = JSON_THROW_ON_ERROR;
      if ($this->ppParseWhole) {
        $contents = $reader->getContents();
        yield json_decode($contents, true, 512, $flags);
      } else {
        while (true) {
          try {
            $line = $reader->readLine();
            yield json_decode($line, true, 512, $flags);
          } catch (EOFException $e) {
            break;
          }
        }
      }
    } 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*/[
    'isParseWhole' => 'parse_whole',
  ];
  const _AUTO_SETTERS = /*autogen*/[
    'setInput' => 'input',
    'setParseWhole' => 'parse_whole',
  ];
  #--autogen-dynamic--
}
