<?php

namespace Myvetshop\Module\Clinique\Import\Kalivet\ImportFile;

/**
 * @implements \Iterator<int, array<mixed>>
 */
class ImportFileParser implements \Iterator
{
    /**
     * @var resource
     */
    protected $stream;

    protected ?string $section = null;

    protected int $i = 0;

    /**
     * @var array<mixed>|null
     */
    protected ?array $datum = null;

    protected function readLine(): ?string
    {
        $line = \fgets($this->stream, 16384);

        return false === $line ? null : $line;
    }

    protected function parseSection(string $row): ?string
    {
        if (\strpos($row, '### ') === 0) {
            return \substr($row, 4);
        }

        return null;
    }

    /**
     * @param resource $stream
     */
    public function __construct($stream)
    {
        $this->stream = $stream;
    }

    public function current()
    {
        \assert(\is_array($this->datum));

        return $this->datum;
    }

    public function next()
    {
        $this->datum = null;

        $ct = 0;

        while (null === $this->datum && null !== ($line = $this->readLine())) {
            ++$ct;
            ++$this->i;

            $section = $this->parseSection($line);
            if (null !== $section) {
                $this->section = \trim($section);
                continue;
            }

            $datum = \json_decode($line, true);
            if (!\is_array($datum)) {
                if (!empty(\trim($line))) {
                    throw new \Exception($line);
                } else {
                    continue;
                }
            }

            $this->datum = $datum;
        }
    }

    public function key()
    {
        return $this->i;
    }

    public function valid(): bool
    {
        return null !== $this->section && null !== $this->datum;
    }

    public function rewind(): void
    {
        \rewind($this->stream);
        $this->section = null;
        $this->datum = null;
        $this->i = 0;

        $this->next();
    }

    /**
     * @return string|null
     */
    public function getSection(): ?string
    {
        return $this->section;
    }
}
