<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Ui\Components\Products\Listing;

use Magento\Ui\Component\MassAction;
use Magento\Framework\AuthorizationInterface;
use Magento\Framework\View\Element\UiComponent\ContextInterface;

class MassActions extends MassAction
{
    public const TRANSFER_ACL_RESOURCE = 'WriteTextAI_WriteTextAI::transfer';

    public const GENERATE_ACL_RESOURCE = 'WriteTextAI_WriteTextAI::generate';

    /**
     * @var AuthorizationInterface
     */
    protected $authorization;

    /**
     * Constructor
     *
     * @param ContextInterface $context
     * @param AuthorizationInterface $authorization
     * @param array $components
     * @param array $data
     */
    public function __construct(
        ContextInterface $context,
        AuthorizationInterface $authorization,
        array $components = [],
        array $data = []
    ) {
        $this->authorization = $authorization;

        parent::__construct(
            $context,
            $components,
            $data
        );
    }

    /**
     * @inheritDoc
     */
    public function prepare(): void
    {
        $disabledComponentsCount = 0;
        $childComponents = $this->getChildComponents();
        $childComponentsCount = count($childComponents);

        if ($childComponentsCount > 0) {
            foreach ($childComponents as $actionComponent) {
                $componentConfig = $actionComponent->getConfiguration();
                switch ($componentConfig['type']) {
                    case 'full_automation':
                    case 'transfer':
                        if (!$this->authorization->isAllowed(self::TRANSFER_ACL_RESOURCE)) {
                            $componentConfig['actionDisable'] = true;
                            $actionComponent->setData('config', $componentConfig);
                            $disabledComponentsCount++;
                        }

                        break;
                    case 'generate':
                        if (!$this->authorization->isAllowed(self::GENERATE_ACL_RESOURCE)) {
                            $componentConfig['actionDisable'] = true;
                            $actionComponent->setData('config', $componentConfig);
                            $disabledComponentsCount++;
                        }
                        
                        break;
                    default:
                        break;
                }
            }
        }

        if ($disabledComponentsCount === $childComponentsCount) {
            $config = $this->getConfiguration();
            $config['componentDisabled'] = true;
            $this->setData('config', $config);
        }

        parent::prepare();
    }
}
