<?php
namespace Newland\NeosMetaTags\Service;

/*
 * This file is part of the "neos-meta-tags" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Mvc\ActionRequest;
use Neos\Media\Domain\Model\AssetInterface;
use Neos\Media\Domain\Service\AssetService;

class ThumbnailService
{
    /**
     * @var \Neos\Media\Domain\Service\ThumbnailService
     * @Flow\Inject()
     */
    protected $thumbnailService;
    /**
     * @var AssetService
     * @Flow\Inject()
     */
    protected $assetService;

    public function getThumbnailDataFromExternalImage(string $imageUrl): array
    {
        try {
            $data = getimagesize($imageUrl);
            return [
                'src' => $imageUrl,
                'height' => $data[0],
                'width' => $data[1],
            ];
        } catch (\Exception $e) {
            return [];
        }
    }

    public function getThumbnailDataFromAsset(
        AssetInterface $image,
        string $preset,
        ActionRequest $request
    ): ?array {
        $thumbnailConfiguration = $this->thumbnailService->getThumbnailConfigurationForPreset($preset);
        $thumbnailData = $this->assetService->getThumbnailUriAndSizeForAsset($image, $thumbnailConfiguration, $request);

        return $thumbnailData;
    }
}
