<?php
declare(strict_types=1);

namespace FiloBlu\Refilo\Block\Adminhtml\ConnectorConfiguration;

use FiloBlu\Refilo\Remote\Connector\ConnectorPool;
use Magento\Backend\Block\Widget\Button\SplitButton as WidgetSlitButton;
use Magento\Backend\Block\Widget\Container;
use Magento\Backend\Block\Widget\Context;

/**
 * Class SplitButton
 * @package FiloBlu\Refilo\Block\Adminhtml\ConnectorConfiguration
 */
class SplitButton extends Container
{

    /**
     * @var ConnectorPool
     */
    private $connectorFactory;

    /**
     * SplitButton constructor.
     * @param Context $context
     * @param ConnectorPool $connectorFactory
     * @param array $data
     */
    public function __construct(
        Context $context,
        ConnectorPool $connectorFactory,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->connectorFactory = $connectorFactory;
    }

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

        return parent::_prepareLayout();
    }

    /**
     * @return array
     */
    protected function getConnectorList(): array
    {
        $list = [];
        $i = 0;
        foreach ($this->connectorFactory->getAll() as $name => $connector) {
            $list["create_connector_{$i}"] = [
                'label'   => __($name),
                'onclick' => 'setLocation("' . $this->getUrl('*/*/edit', ['type' => $name]) . '")'
            ];
            $i++;
        }

        return $list;
    }
}
