<?php
namespace Newland\NeosCommon\Service;

use GuzzleHttp\Client as GuzzleClient;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Cache\CacheManager;

/**
 * @Flow\Scope("singleton")
 */
class VimeoPreviewService
{
    const CACHE_NAME = 'Newland_NeosCommon-Video';
    const CACHE_KEY = 'vimeo-information-{videoId}';
    const SIZE_SMALL = 'small';
    const SIZE_MEDIUM = 'medium';
    const SIZE_LARGE = 'large';

    /**
     * @Flow\Inject
     * @var CacheManager
     */
    protected $cacheManager;

    /**
     * @var GuzzleClient
     */
    protected $httpClient;

    public function __construct()
    {
        $this->httpClient = new GuzzleClient([ 'base_uri' => 'https://vimeo.com/api/v2/' ]);
    }

    /**
     * @param string $videoId
     * @param string $size
     * @return string|null
     */
    public function getPreviewImage(string $videoId, string $size = self::SIZE_LARGE)
    {
        $information = $this->getInformationFromCacheOrApi($videoId);

        $key = 'thumbnail_' . $size;
        if (property_exists($information, $key)) {
            return $information->{$key};
        }

        return null;
    }

    private function getInformationFromCacheOrApi(string $videoId): \stdClass
    {
        $cache = $this->cacheManager->getCache(static::CACHE_NAME);
        $cacheKey = str_replace(static::CACHE_KEY, '{videoId}', $videoId);

        if ($cache->has($cacheKey)) {
            return $cache->get($cacheKey);
        }

        $information = $this->fetchVideoInformationFromApi($videoId);
        $cache->set($cacheKey, $information);
        return $information;
    }

    private function fetchVideoInformationFromApi(string $videoId): \stdClass
    {
        $response = $this->httpClient->get('video/' . $videoId . '.json');
        $result = json_decode($response->getBody(), false);

        if (!$result || \count($result) === 0 || $response->getStatusCode() !== 200) {
            return (object) [];
        }

        return $result[0];
    }
}
