<?php

namespace FiloBlu\Esb\Model\Saver;

use FiloBlu\Esb\Api\ConsumerConfigurationRepositoryInterface;
use FiloBlu\Esb\Api\ConsumerResolverInterface;
use FiloBlu\Esb\Api\ObjectTypeSaverInterface;
use FiloBlu\Esb\Api\ProducerConfigurationRepositoryInterface;
use FiloBlu\Esb\Api\ProducerResolverInterface;
use FiloBlu\Esb\Framework\Data\AbstractFilterableByEndpointOptions;
use FiloBlu\Esb\Model\ObjectTypeSaverResolverInterface;
use Magento\Framework\App\RequestInterface;

/**
 * Class Options
 * @package FiloBlu\Esb\Model\Saver
 */
class Options extends AbstractFilterableByEndpointOptions
{
    /**
     * @var ObjectTypeSaverResolverInterface
     */
    private $objectTypeSaverResolver;

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

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

        $descriptor = $this->getObjectTypeDescriptor();
        $result = $this->objectTypeSaverResolver->getAll();

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

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

        return $this->options;
    }
}
