<?php
namespace nur\mapper\line;

use nur\b\io\EOFException;
use nur\b\io\IReader;
use nur\b\io\Tfilter;
use nur\b\params\Tparametrable;
use nur\data\types\Metadata;
use nur\mapper\base\encoding_utils;
use nur\mapper\base\Producer;
use nur\mapper\base\Tencoding;
use nur\reader;

/**
 * Class LineReader
 *
 * --autogen-methods--
 */
class LineReader extends Producer {
  use Tparametrable, Tencoding, Tfilter;

  function __construct($input=null) {
    parent::__construct();
    $this->pp_setInput($input);
  }

  function setEncodingFilter(string $from, string $to="utf-8"): void {
    $this->_setEncodingFilter($from, $to);
  }

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

  static function _get_parametrable_params_schema(): array {
    return array_merge(self::PARAMETRABLE_PARAMS_SCHEMA
      , encoding_utils::PARAMETRABLE_PARAMS_SCHEMA);
  }

  protected function afterSetParametrableParams(array $modifiedKeys, ?Metadata $md=null): void {
    $this->encodingInput__afterSetParametrableParams($modifiedKeys);
  }

  protected $ppInput;

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

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

  protected function setup(): void {
    if ($this->reader === null) {
      $this->reader = reader::with($this->ppInput);
      $this->_rwAppendFilters($this->reader);
    }
  }

  function producer() {
    $reader = $this->reader;
    while (true) {
      try {
        yield $reader->readLine();
      } catch (EOFException $e) {
        break;
      }
    }
  }

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

  #############################################################################
  const _AUTOGEN_CONSTS = [
    "" => [self::class, "_autogen_consts", true],
  ];
  const _AUTOGEN_LITERALS = null;
  const _AUTOGEN_METHODS = null;
  const _AUTO_GETTERS = null;
  const _AUTO_SETTERS = null;
  #--autogen-dynamic--
}
