<?php
/**
 * Created by Glee Ltd.
 * User: Hieu
 * Date: 05-Mar-18
 * Time: 4:16 PM
 * Description:
 */

namespace Hura8\System;


class Youtube
{

    public static function buildVideoUrl($video_id) {
        return 'https://www.youtube.com/watch?v='.$video_id;
    }

    /* 08-06-2016
     * @description: get youtube thumnail
     * @param url youtube's video url
     * @param size thumnail size: default|high|medium
     * @return url or ''
    */
    public static function getYouTubeThumbnail($url){
        $id = static::getVideoId($url);
        if($id) {
            return "https://img.youtube.com/vi/".$id."/hqdefault.jpg";
        }

        return '';
    }

    public static function getVideoId($url) {
        if(!$url) return '';

        // direct video code
        if(!Url::isUrlValid($url)) return $url;

        //$url = https://www.youtube.com/watch?v=9246msCh7x4
        $pattern =
            '%^# Match any youtube URL
				(?:https?://)?  # Optional scheme. Either http or https
				(?:www\.)?      # Optional www subdomain
				(?:             # Group host alternatives
				  youtu\.be/    # Either youtu.be,
				| youtube\.com  # or youtube.com
				  (?:           # Group path alternatives
					/embed/     # Either /embed/
				  | /v/         # or /v/
				  | .*v=        # or /watch\?v=
				  )             # End path alternatives.
				)               # End host alternatives.
				([\w-]{10,12})  # Allow 10-12 for 11 char youtube id.
				($|&).*         # if additional parameters are also in query string after video id.
				$%x'
        ;

        if (preg_match($pattern, $url, $matches)) {
            return $matches[1];
        }

        return "";
    }

    //21-12-2012
    //show Youtube Video code from given youtube url
    public static function buildHtml($url, $method='iframe', $video_width=560, $video_height=315, $auto_play=1) {
        $youtube_id = self::getVideoId($url);

        if ($youtube_id) {
            switch ($method){
                case "iframe";
                    if($auto_play == 1) {
                        return "<iframe width=\"".$video_width."\" height=\"".$video_height."\" src=\"https://www.youtube.com/embed/".$youtube_id."?rel=0&autoplay=1\" frameborder=\"0\" allowfullscreen></iframe>";
                    }else{
                        return "<iframe width=\"".$video_width."\" height=\"".$video_height."\" src=\"https://www.youtube.com/embed/".$youtube_id."?rel=0\" frameborder=\"0\" allowfullscreen></iframe>";
                    }
                    break;
            }
        }
        return "";
    }

}
