<?php

namespace FiloBlu\Esb\Block\Adminhtml\Producer;

use FiloBlu\Esb\Api\ProducerResolverInterface;
use Magento\Backend\Block\Widget\Button\SplitButton;
use Magento\Backend\Block\Widget\Container;
use Magento\Backend\Block\Widget\Context;

/**
 * Class ProducerSplitButton
 * @package FiloBlu\Esb\Block\Adminhtml\Producer
 */
class ProducerSplitButton extends Container
{
    /**
     * @var ProducerResolverInterface
     */
    private $producerResolver;

    /**
     * @param Context $context
     * @param ProducerResolverInterface $producerResolver
     * @param array $data
     */
    public function __construct(
        Context $context,
        ProducerResolverInterface $producerResolver,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->producerResolver = $producerResolver;
    }

    /**
     * @return Container
     */
    protected function _prepareLayout()
    {
        $this->buttonList->add('add_new', [
            'id' => 'filoblu_esb_create_producer',
            'label' => __('Add Producer'),
            'class' => 'add',
            'button_class' => '',
            'class_name' => SplitButton::class,
            'options' => $this->getProducerList(),
        ]);

        return parent::_prepareLayout();
    }

    /**
     * @return array
     */
    protected function getProducerList(): array
    {
        $list = [];
        $i = 0;
        foreach ($this->producerResolver->getAll() as $producer) {
            $list["create_producer_{$i}"] = [
                'label' => __($producer->getName()),
                'onclick' => 'setLocation("' . $this->getUrl('*/*/edit', ['type' => $producer->getUniqueName()]) . '")'];
            $i++;
        }

        return $list;
    }
}
