<?php
declare(strict_types=1);

namespace FiloBlu\Refilo\Ui\Component\Indexer\Listing;

use FiloBlu\Refilo\Remote\Connector\ConnectorConfigurationInterface;
use FiloBlu\Refilo\Remote\Connector\ConnectorConfigurationRepositoryInterface;
use Magento\Framework\View\Element\UiComponent\ContextInterface;

/**
 *
 */
class MassAction extends \Magento\Ui\Component\MassAction
{
    /**
     * @var ConnectorConfigurationRepositoryInterface
     */
    private $connectorConfigurationRepository;


    /**
     * @param ContextInterface $context
     * @param ConnectorConfigurationRepositoryInterface $connectorConfigurationRepository
     * @param array $components
     * @param array $data
     */
    public function __construct(ContextInterface                          $context,
                                ConnectorConfigurationRepositoryInterface $connectorConfigurationRepository,
                                array                                     $components = [],
                                array                                     $data = [])
    {
        parent::__construct($context, $components, $data);
        $this->connectorConfigurationRepository = $connectorConfigurationRepository;
    }

    public function prepare()
    {
        parent::prepare();

        if (!isset($this->_data['config']['actions'])) {
            $this->_data['config']['actions'] = [];
        }

        $result = $this->connectorConfigurationRepository->getList();

        /** @var ConnectorConfigurationInterface $connectorConfiguration */
        foreach ($result->getItems() as $connectorConfiguration) {
            $name = $connectorConfiguration->getName();
            $id = $connectorConfiguration->getId();
            $this->_data['config']['actions'][] = [
                'component' => 'uiComponent',
                'type'      => "assign_connector_{$id}",
                'label'     => __('Assign %1', $name),
                'url'       => $this->getContext()->getUrl(
                    'filoblu_refilo/indexer/massConnector',
                    ['connector' => $id]
                ),
                'confirm'   => [
                    'title'   => __('Assign Connector'),
                    'message' => __('Are you sure you want to assign %1 connector to selected items?', $name)
                ]
            ];
        }
    }
}
