<?php

namespace FiloBlu\Esb\Model\Event;

use FiloBlu\Esb\Api\ConsumerConfigurationRepositoryInterface;
use FiloBlu\Esb\Api\ConsumerResolverInterface;
use FiloBlu\Esb\Api\Data\EventConfigurationInterface;
use FiloBlu\Esb\Api\EventConfigurationRepositoryInterface;
use FiloBlu\Esb\Api\ProducerConfigurationRepositoryInterface;
use FiloBlu\Esb\Api\ProducerResolverInterface;
use FiloBlu\Esb\Framework\Data\AbstractFilterableByEndpointOptions;
use Magento\Framework\App\RequestInterface;

/**
 * Class Options
 * @package FiloBlu\Esb\Model\Event
 */
class Options extends AbstractFilterableByEndpointOptions
{

    /** @var EventConfigurationRepositoryInterface */
    private $repository;

    /**
     * Options constructor.
     * @param RequestInterface $request
     * @param ProducerConfigurationRepositoryInterface $producerConfigurationRepository
     * @param ConsumerConfigurationRepositoryInterface $consumerConfigurationRepository
     * @param ProducerResolverInterface $producerResolver
     * @param ConsumerResolverInterface $consumerResolver
     * @param EventConfigurationRepositoryInterface $repository
     */
    public function __construct(
        RequestInterface $request,
        ProducerConfigurationRepositoryInterface $producerConfigurationRepository,
        ConsumerConfigurationRepositoryInterface $consumerConfigurationRepository,
        ProducerResolverInterface $producerResolver,
        ConsumerResolverInterface $consumerResolver,
        EventConfigurationRepositoryInterface $repository
    ) {
        parent::__construct(
            $request,
            $producerConfigurationRepository,
            $consumerConfigurationRepository,
            $producerResolver,
            $consumerResolver
        );
        $this->repository = $repository;
    }

    /**
     * @return array|null
     */
    public function toOptionArray()
    {
        if (!empty($this->options)) {
            return $this->options;
        }

        $descriptor = $this->getObjectTypeDescriptor();
        $result = $this->repository->getList();

        $this->options[] = [
            'value' => null,
            'label' => 'None'
        ];

        /** @var EventConfigurationInterface $item */
        foreach ($result->getItems() as $item) {
            if ($descriptor !== null && !$item->getBaseEvent()->isSuitableFor($descriptor)) {
                continue;
            }

            $this->options[] = [
                'value' => $item->getEventCode(),
                'label' => $item->getLabel()
            ];
        }

        return $this->options;
    }
}
