<?php

namespace FiloBlu\Esb\Model\Loader;

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

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

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

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

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

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

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

        return $this->options;
    }
}
