<?php

namespace FiloBlu\Esb\Block\Adminhtml\Consumer;

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

/**
 * Class ConsumerSplitButton
 * @package FiloBlu\Esb\Block\Adminhtml\Consumer
 */
class ConsumerSplitButton extends Container
{
    /**
     * @var ConsumerResolverInterface
     */
    protected $consumerResolver;

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

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

        return parent::_prepareLayout();
    }

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

        return $list;
    }
}
