<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Plugins\CatalogWidget\Block\Product;

use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\CatalogWidget\Block\Product\ProductsList;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\EntityManager\MetadataPool;
use Magento\Framework\Exception\LocalizedException;

/**
 * @class ProductsListPlugin
 * @package FiloBlu\Refilo\Plugins
 */
class ProductsListPlugin
{

    /**
     * Limit the product shown to the value given to the form
     *
     * @param ProductsList $subject
     * @param Collection $result
     * @return Collection
     * @see \Magento\CatalogWidget\Block\Product\ProductsList::createCollection
     */
    public function afterCreateCollection(ProductsList $subject, Collection $result)
    {
        if (!$subject->getProductsCount()) {
            return $result;
        }

        if (count($result->getItems()) <= $subject->getProductsCount()) {
            return $result;
        }

        /** reload the items with the limitations already set in the query */
        return $result->clear()->load();
    }
}
