<?php

declare(strict_types=1);

namespace Seka\Portal\Modul\Statistiky\Repositories\Eloquent\Transformers\Summary\DataTables;

use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use Iterator;
use JsonSerializable;

/**
 * Class DataTableAbstract
 *
 * @package Seka\Portal\Modul\Statistiky\Repositories\Eloquent\Transformers\Summary\DataTables
 */
abstract class DataTableAbstract implements DataTableContract, Iterator, Arrayable, Jsonable, JsonSerializable
{
    /**
     * @var \Seka\Portal\Modul\Statistiky\Repositories\Eloquent\Transformers\Summary\DataTables\DataTableRowContract[]
     */
    protected array $rows = [];
    /**
     * @var int
     */
    private int $positionInRows = 0;

    /**
     * @param \Seka\Portal\Modul\Statistiky\Repositories\Eloquent\Transformers\Summary\DataTables\DataTableRowContract $row
     *
     * @return $this
     */
    public function addRow(DataTableRowContract $row): self
    {
        $this->rows[] = $row;

        return $this;
    }

    /**
     * @param int $options
     *
     * @return string
     */
    public function toJson($options = 0): string
    {
        return json_encode($this->toArray(), $options);
    }

    /**
     * @return array
     */
    public function toArray(): array
    {
        $o = [];

        foreach ($this->rows as $row) {
            $o[] = $row->toArray();
        }

        return $o;
    }

    /**
     * @return array
     */
    public function jsonSerialize(): array
    {
        return $this->toArray();
    }

    /**
     * @return \Seka\Portal\Modul\Statistiky\Repositories\Eloquent\Transformers\Summary\DataTables\DataTableRowContract
     */
    public function current(): DataTableRowContract
    {
        return $this->rows[$this->positionInRows];
    }

    /**
     * @return void
     */
    public function next()
    {
        ++$this->positionInRows;
    }

    /**
     * @return int
     */
    public function key(): int
    {
        return $this->positionInRows;
    }

    /**
     * @return bool
     */
    public function valid(): bool
    {
        return isset($this->rows[$this->positionInRows]);
    }

    /**
     * @return void
     */
    public function rewind()
    {
        $this->positionInRows = 0;
    }
}
