<?php
declare(strict_types=1);

namespace FiloBlu\Refilo\Controller\Adminhtml\Indexer;

use FiloBlu\Refilo\Remote\IndexerConfiguration\IndexerConfigurationInterface;
use FiloBlu\Refilo\Remote\IndexerConfiguration\IndexerConfigurationRepositoryInterface;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Api\SearchCriteriaBuilderFactory;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Controller\ResultInterface;

/**
 *
 */
class MassEnableMemoryOptimization extends Action
{
    /**
     * @var IndexerConfigurationRepositoryInterface
     */
    private $indexerConfigurationRepository;

    /**
     * @var SearchCriteriaBuilderFactory
     */
    private $searchCriteriaBuilderFactory;

    /**
     * @param Context $context
     * @param IndexerConfigurationRepositoryInterface $indexerConfigurationRepository
     * @param SearchCriteriaBuilderFactory $searchCriteriaBuilderFactory
     */
    public function __construct(
        Context                                 $context,
        IndexerConfigurationRepositoryInterface $indexerConfigurationRepository,
        SearchCriteriaBuilderFactory            $searchCriteriaBuilderFactory
    ) {
        parent::__construct($context);
        $this->indexerConfigurationRepository = $indexerConfigurationRepository;
        $this->searchCriteriaBuilderFactory = $searchCriteriaBuilderFactory;
    }

    /**
     * Execute action based on request and return result
     *
     * @return ResultInterface|ResponseInterface
     */
    public function execute()
    {
        $request = $this->getRequest();
        $status = (int)$request->getParam('enable_memory_optimization');

        $excluded = $request->getParam('excluded');
        $selected = $request->getParam('selected');

        $searchCriteriaBuilder = $this->searchCriteriaBuilderFactory->create();

        if ($selected !== null) {
            $searchCriteriaBuilder->addFilter(IndexerConfigurationInterface::ID, $selected, 'in');
        }

        if ($excluded !== null) {
            $searchCriteriaBuilder->addFilter(IndexerConfigurationInterface::ID, $excluded, 'nin');
        }

        $result = $this->indexerConfigurationRepository->getList($searchCriteriaBuilder->create());

        /** @var IndexerConfigurationInterface $indexerConfiguration */
        foreach ($result->getItems() as $indexerConfiguration) {
            $indexerConfiguration->setEnabledMemoryOptimization((bool)$status);
            $this->indexerConfigurationRepository->save($indexerConfiguration);
        }

        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        $resultRedirect->setPath('*/*/');
        return $resultRedirect;
    }

    /**
     * @return bool
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('FiloBlu_Refilo::Refilo');
    }
}
