<?php
namespace Newland\NeosNodeTypes\Video;

use Newland\NeosNodeTypes\Exception\UnknownVideoException;
use Newland\NeosNodeTypes\Service\VimeoPreviewService;
use Neos\Flow\Annotations as Flow;

class VimeoVideo extends AbstractVideo
{

    /** @var string */
    private $videoId;

    /**
     * @var VimeoPreviewService
     * @Flow\Inject()
     */
    protected $videoPreview;

    public function __construct(string $url)
    {
        $this->videoId = $this->extractVideoId($url);
    }

    public function getEmbedUrl(): string
    {
        return '//player.vimeo.com/video/' . $this->videoId . '?autoplay=1';
    }

    public function getPreviewUrl(): string
    {
        return (string) $this->videoPreview->getPreviewImage($this->videoId, VimeoPreviewService::SIZE_LARGE);
    }

    private function extractVideoId(string $url): string
    {
        $parsedUrl = parse_url($url);
        if ($parsedUrl === false) {
            throw new UnknownVideoException('The url ' . $url . ' cannot be parsed.');
        }

        if (array_key_exists('path', $parsedUrl)) {
            $pathParts = explode('/', $parsedUrl['path']);
            return (string) array_pop($pathParts);
        }

        throw new UnknownVideoException('The url ' . $url . ' cannot be parsed as Vimeo URL.');
    }
}
