<?php

declare(strict_types=1);

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

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

/**
 * Class EChartSourceAbstract
 *
 * @package Seka\Portal\Modul\Statistiky\Repositories\Eloquent\Transformers\Summary\ECharts
 */
abstract class EChartSourceAbstract implements EChartSourceContract, Iterator, Arrayable, Jsonable, JsonSerializable
{
    /**
     * @var \Seka\Portal\Modul\Statistiky\Repositories\Eloquent\Transformers\Summary\ECharts\EChartSourceItemContract[]
     */
    protected array $items = [];
    /**
     * @var int
     */
    private int $positionInRows = 0;

    /**
     * @param \Seka\Portal\Modul\Statistiky\Repositories\Eloquent\Transformers\Summary\ECharts\EChartSourceItemContract $sourceItem
     *
     * @return $this
     */
    public function addItem(EChartSourceItemContract $sourceItem): self
    {
        $this->items[] = $sourceItem;

        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->items as $item) {
            $o[] = $item->toArray();
        }

        return $o;
    }

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

    /**
     * @return \Seka\Portal\Modul\Statistiky\Repositories\Eloquent\Transformers\Summary\ECharts\EChartSourceItemContract
     */
    public function current(): EChartSourceItemContract
    {
        return $this->items[$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->items[$this->positionInRows]);
    }

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

    /**
     * @return bool
     */
    public function isEmpty(): bool
    {
        return count($this->items) < 1;
    }

    /**
     * @return bool
     */
    public function isNotEmpty(): bool
    {
        return !$this->isEmpty();
    }
}
