<?php

/**
 * PicoVideoEmbed - Responsive peerube, vimeo and youtube embeds in shortcode format
 * 
 * @author  Jurij Podgoršek <g1smo@git.kompot.si>
 * @license https://www.gnu.org/licenses/agpl-3.0.en.html
 * @version 0.1
 */
class PicoVideoEmbed extends AbstractPicoPlugin
{
    /**
     * API version used by this plugin
     *
     * @var int
     */
    const API_VERSION = 3;

    /**
     * This plugin depends on ...
     *
     * @see AbstractPicoPlugin::$dependsOn
     * @var string[]
     */
    protected $dependsOn = array();


    const SHORTCODE = '#\[video .+?\]#i';

    /**
	 * Triggered after Pico has prepared the raw file contents for parsing
	 *
	 * @see	Pico::parseFileContent()
	 * @see	DummyPlugin::onContentParsed()
	 * @param  string &$content prepared file contents for parsing
	 * @return void
	 */
    public function onContentParsed(&$content)
    {
    if (stripos($content, '[video') !== false) {
        // Search for Embed shortcodes allover the content
        preg_match_all(self::SHORTCODE, $content, $matches);

        // Make sure we found some shortcodes
        if (count($matches[0]) > 0) {

            // Walk through shortcodes one by one
            foreach ($matches[0] as $match) {

                // First, try youtube
                // Get youtube like and video ID (Ref:http://stackoverflow.com/questions/3717115/regular-expression-for-youtube-links/3726073#3726073)
                preg_match(self::YOUTUBE_REGEX, $match, $embed_link);
                if (count($embed_link) > 1) {
                    $content = preg_replace(self::SHORTCODE, $this->getYoutubeEmbed($embed_link), $content, 1);
                    continue;
                }

                // Next, we try vimeo
                preg_match(self::VIMEO_REGEX, $match, $embed_link);
                if (count($embed_link) > 1) {
                    $content = preg_replace(self::SHORTCODE, $this->getVimeoEmbed($embed_link), $content, 1);
                    continue;
                }

                // Otherwise, it's peertube <3
                preg_match(self::PEERTUBE_REGEX, $match, $embed_link);
                if (count($embed_link) > 1) {
                    $content = preg_replace(self::SHORTCODE, $this->getPeertubeEmbed($embed_link), $content, 1);
                    continue;
                }
            }
        }
    }
    }

    const YOUTUBE_REGEX = '#http(?:s)?\:\/\/(?:www\.)?youtu(?:be\.com/watch\?v=|\.be/|be\.com/embed/)([\w\-]+)(&(amp;)?[\w\?=]*)?#s';
    private function getYoutubeEmbed(array $embed_link) {
        return '<div class="pico-video-embed">'
            . '<iframe id="ytID" width="500" height="480" src="https://www.youtube.com/embed/' . $embed_link[1] . '" frameborder="0" allowfullscreen></iframe>'
            . '</div>';
    }

    const VIMEO_REGEX = '#http(?:s)?\:\/\/(?:www\.)?(?:player\.)?vimeo\.com/(?:video/)?([0-9]+)(-:\?.+)?#s';
    private function getVimeoEmbed(array $embed_link) {
        return '<div class="pico-video-embed">'
            . '<iframe width="560" height="315" sandbox="allow-same-origin allow-scripts allow-popups" src="https://player.vimeo.com/video/' . $embed_link[1] . '?warningTitle=0" frameborder="0" allowfullscreen></iframe>'
            . '</div>';
    }

    const PEERTUBE_REGEX = '#(http(?:s)?)\:\/\/([a-zA-Z0-9](?:(?:[a-zA-Z0-9-]*|(?<!-)\.(?![-.]))*[a-zA-Z0-9]+)?)(?:/videos/embed|/videos/watch|/w)/([0-9a-zA-Z-]+)/?#s';
    private function getPeertubeEmbed(array $embed_link) {
        return '<div class="pico-video-embed">'
            . '<iframe width="560" height="315" sandbox="allow-same-origin allow-scripts allow-popups" src="' . $embed_link[1] . '://' . $embed_link[2] . '/videos/embed/' . $embed_link[3] . '?warningTitle=0" frameborder="0" allowfullscreen></iframe>'
            . '</div>';
    }
    
	/**
	 * Triggered after Pico has rendered the page
	 *
	 * @param  string &$output contents which will be sent to the user
	 * @return void
	 */
	public function onPageRendered(&$output)
	{
        // Add embed css
		$output = str_replace('</head>', ($this->getStyleHeader() . '</head>'), $output);
	}

    private function getStyleHeader() {
        $header = '<style type="text/css">'
                . '.pico-video-embed { position: relative; padding-bottom: 56.25%; border: 0;}'
                . '.pico-video-embed iframe, .video-container object, .video-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0;}'
                . '</style>';
        return $header;
    }
}
