<?php
/**
 * @author Aitoc Team
 * @copyright Copyright (c) 2020 Aitoc (https://www.aitoc.com)
 * @package Aitoc_PreOrders
 */

/**
 * Copyright © 2018 Aitoc. All rights reserved.
 * Developed by Alex Yakimovich
 */

namespace Aitoc\PreOrders\Plugin\Catalog\Model\Layer;

use Magento\Framework\Registry;
use Aitoc\PreOrders\Api\Data\Source\RegistryNameInterface;
use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection as CatalogSearchFulltextCollection;
use Magento\Catalog\Model\Layer\Search as LayerSearch;

/**
 * Class Search
 */
class Search
{
    /**
     * @var Registry
     */
    private $registry;

    /**
     * @param Registry $registry
     */
    public function __construct(Registry $registry)
    {
        $this->registry = $registry;
    }

    /**
     * @param LayerSearch $subject
     * @param CatalogSearchFulltextCollection $result
     * @return CatalogSearchFulltextCollection
     */
    public function afterGetProductCollection(
        LayerSearch $subject,
        CatalogSearchFulltextCollection $result
    ) {
        $productIds = $result->getColumnValues($result->getIdFieldName());
        if ($this->registry->registry(RegistryNameInterface::CURRENT_SEARCH_PRODUCT_IDS)) {
            $this->registry->unregister(RegistryNameInterface::CURRENT_SEARCH_PRODUCT_IDS);
        }
        $this->registry->register(RegistryNameInterface::CURRENT_SEARCH_PRODUCT_IDS, $productIds);
        
        return $result;
    }
}
