<?php
/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Advanced Product Reviews Base for Magento 2
 */

namespace Amasty\AdvancedReview\Ui\Component\Listing\MassActions;

use Magento\Framework\Data\OptionSourceInterface;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\UiComponent\ContextInterface;

class MassAction extends \Magento\Ui\Component\Action
{
    /**
     * @var UrlInterface
     */
    private $urlBuilder;

    /**
     * @var OptionSourceInterface
     */
    private $optionSource;

    public function __construct(
        ContextInterface $context,
        UrlInterface $urlBuilder,
        ?OptionSourceInterface $optionSource = null,
        array $components = [],
        array $data = [],
        $actions = null
    ) {
        parent::__construct($context, $components, $data, $actions);
        $this->optionSource = $optionSource;
        $this->urlBuilder = $urlBuilder;
    }

    /**
     * Prepare params array for urlBuilder
     *
     * @param string|int $optionValue
     *
     * @return array
     */
    public function getUrlParams($optionValue)
    {
        return ['key' => $optionValue];
    }

    /**
     * Complete Mass actions with external options
     */
    public function prepare()
    {
        $options = $this->optionSource->toOptionArray();
        foreach ($options as $option) {
            $this->actions[] = [
                'type' => strtolower($option['label']),
                'label' => $option['label'],
                'url' => $this->urlBuilder->getUrl(
                    $this->_data['config']['massActionUrl'],
                    $this->getUrlParams($option['value'])
                )
            ];
        }
        parent::prepare();
    }
}
