<?php
namespace nur\sery\file\csv;

use nur\sery\file;
use nur\sery\file\FileReader;

class CsvReader extends AbstractReader {
  use TAbstractReader;

  function __construct($input, ?array $params=null) {
    parent::__construct($input, $params);
    $this->csvFlavour = $params["csv_flavour"] ?? null;
    $this->inputEncoding = $params["input_encoding"] ?? null;
  }

  protected ?string $csvFlavour;

  protected ?string $inputEncoding;

  function getIterator() {
    $reader = new FileReader(file::fix_dash($this->input));
    $inputEncoding = $this->inputEncoding;
    if ($inputEncoding !== null) {
      $reader->appendFilter("convert.iconv.$inputEncoding.utf-8");
    }
    $reader->setCsvFlavour($this->csvFlavour);
    while (($row = $reader->fgetcsv()) !== null) {
      foreach ($row as &$col) {
        $this->verifixCol($col);
      }; unset($col);
      if ($this->cookRow($row)) {
        yield $row;
        $this->idest++;
      }
      $this->isrc++;
    }
    $reader->close();
  }
}
