<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Remote\Entity\Provider;

use FiloBlu\Refilo\Remote\Entity\EntityProviderInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Api\Data\WebsiteInterface;

/**
 *
 */
class UrlProvider extends BaseProvider
{

    /**
     * @var array
     */
    private $urlProviders;

    /**
     * @var StoreInterface
     */
    private $store;

    /**
     * @param ScopeConfigInterface $scopeConfig
     * @param EntityProviderInterface[] $urlProviders
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        array $urlProviders = []
    ) {
        $this->urlProviders = $urlProviders;
        parent::__construct($scopeConfig);
    }

    /**
     * @return void
     */
    #[\ReturnTypeWillChange]
    public function rewind()
    {
        $this->items = [];
        if (empty($this->ids)) {
            return;
        }

        foreach ($this->urlProviders as $urlProvider) {
            $urlProvider->rewind();
//            $this->items = array_merge(iterator_to_array($urlProvider->withIds($this->ids)->forStore($this->store)), $this->items);
            foreach (iterator_to_array($urlProvider->withIds($this->ids)->forStore($this->store)) as $item){
                $this->items[] = $item;
            }
        }

        if (!$this->hasReadHandler()) {
            return;
        }

        // TODO: Handle pagination
        // Temporary workaround for Morato
        $pageSize = $this->getBulkSize();
        $size = count($this->items);

        while ($size > $pageSize) {
            $data = array_slice($this->items, 0, $pageSize);
            $this->getReadHandler()->onRead($data, $pageSize, $this->getReadHandlerArguments());
            $size -= $pageSize;
        }

        if ($size > 0) {
            $this->getReadHandler()->onRead($this->items, $size, $this->getReadHandlerArguments());
        }
    }

    /**
     * @param StoreInterface $store
     * @return EntityProviderInterface
     */
    public function forStore(StoreInterface $store): EntityProviderInterface
    {
        $this->store = $store;
        return $this;
    }

    /**
     * @param WebsiteInterface $website
     * @return EntityProviderInterface
     */
    public function forWebsite(WebsiteInterface $website): EntityProviderInterface
    {
        return $this;
    }
}
