<?php

declare(strict_types=1);

/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Jet Theme Backend for Magento 2 (System)
 */

namespace Amasty\JetTheme\Model\Product;

use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\Product\Gallery\ReadHandler;
use Magento\Catalog\Model\Product\Image\UrlBuilder as ImageUrlBuilder;

class HoverImageProvider
{
    private const HOVER_IMAGE_COUNT = 2;
    private const IMAGE_DISPLAY_AREA = 'category_page_grid';
    private const IMAGE_TYPE = 'small_image';

    /**
     * @var ReadHandler
     */
    private $readHandler;

    /**
     * @var ImageUrlBuilder
     */
    private $imageUrlBuilder;

    public function __construct(
        ReadHandler $readHandler,
        ImageUrlBuilder $imageUrlBuilder
    ) {
        $this->readHandler = $readHandler;
        $this->imageUrlBuilder = $imageUrlBuilder;
    }

    public function getHoverImages(ProductInterface $product): array
    {
        $this->readHandler->execute($product);
        $productImages = $product->getMediaGalleryImages();

        $images = [];
        $mainImage = $product->getData(self::IMAGE_TYPE) ?? 'no_selection';
        $count = 0;
        $images[] = $this->imageUrlBuilder->getUrl($mainImage, self::IMAGE_DISPLAY_AREA);
        foreach ($productImages as $image) {
            if (self::HOVER_IMAGE_COUNT === $count) {
                break;
            }

            if ($image->getFile() === $mainImage) {
                continue;
            }

            $images[] = $this->imageUrlBuilder->getUrl($image->getFile(), self::IMAGE_DISPLAY_AREA);
            $count++;
        }

        return $images;
    }
}
