<?php

if (!defined('MagicToolboxVideoHelperClassLoaded')) {
    define('MagicToolboxVideoHelperClassLoaded', true);
    class MagicToolboxVideoHelperClass {
        private static $sources = array('youtube' => array(), 'vimeo' => array());

        private static $youtubeImgs = array(
            'thumb1' => '1.jpg',                // 120x90
            'thumb2' => '2.jpg',                // 120x90
            'thumb3' => '3.jpg',                // 120x90
            'def0' => '0.jpg',                  // 480x360
            'def1' => 'default.jpg',            // 120x90
            'middleQuality' => 'mqdefault.jpg', // 320x180
            'highQuality' => 'hqdefault.jpg',   // 480x360
            'maxSize' => 'maxresdefault.jpg'    // 1920x1080
        );

        private static function getType($url) {
            $result = false;

            if (preg_match('/youtube/', $url) || preg_match('/youtu\.be/', $url)) {
                $result = 'youtube';
            } else if (preg_match('/vimeo/', $url)) {
                $result = 'vimeo';
            }

            return $result;
        }

        private static function getYouTobeId($url) {
            $result = false;

            $url = preg_replace('/(>|<)/i', '', $url);
            $url = preg_split('/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/',  $url);

            if ($url && is_array($url) && count($url) > 1) {
                $url = preg_split('/[^0-9a-z_\-]/i', $url[1]);
                if ($url && is_array($url)) {
                    $result = $url[0];
                }
            }

            return $result;
        }

        private static function getVimeoId($url) {
            $result = false;

            if (preg_match('/(?:https?:\/\/)?(?:www.)?(?:player.)?vimeo.com\/(?:[a-z]*\/)*([0-9]{6,11})[?]?.*/', $url, $url)) {
                $result = $url[1];
            }

            return $result;
        }

        private static function getYouTobeImages($id) {
            $result = array();
            $path = 'https://img.youtube.com/vi/';

            foreach (self::$youtubeImgs as $key => $value) {
                $result[$key] = $path.$id.'/'.$value;
            }

            return $result;
        }

        private static function getSimpleYoutubeData($raw) {
            return array(
                'thumbnail' => array( 'url' => $raw['def1'], 'width' => 120, 'height' => 90 ),
                'medium' => array( 'url' => $raw['def0'], 'width' => 480, 'height' => 360 )
            );
        }

        private static function getVimeoImages($id) {
            $result = false;

            $data = file_get_contents('https://vimeo.com/api/v2/video/'.$id.'.php');
            if ($data) {
                $result = unserialize($data);
            }

            return $result;
        }

        private static function getSimpleVimeoData($raw) {
            return array(
                'thumbnail' => array( 'url' => $raw['thumbnail_small'], 'width' => 100, 'height' => 75 ),
                'medium' => array( 'url' => $raw['thumbnail_medium'], 'width' => 200, 'height' => 150 )
            );
        }

        public static function getImages($videoUrl /* string */, $isRaw = false) {
            $result = false;

            if ($videoUrl) {
                $rawData = array();
                $type = self::getType($videoUrl);

                if ($type === 'youtube') {
                    $id = self::getYouTobeId($videoUrl);
                } else {
                    $id = self::getVimeoId($videoUrl);
                }

                if ($type && $id) {
                    if (array_key_exists($id, self::$sources[$type])) {
                        $result = self::$sources[$type][$id];
                        if (!$isRaw) {
                            switch ($type) {
                                case 'youtube':
                                    $result = self::getSimpleYoutubeData($result['raw']);
                                    break;
                                case 'vimeo':
                                    $result = self::getSimpleVimeoData($result['raw']);
                                    break;
                                default:
                                    $result = false;
                            }
                        }
                    } else {
                        $rawData['id'] = $id;
                        $rawData['type'] = $type;
                        $rawData['url'] = $videoUrl;

                        switch ($type) {
                            case 'youtube':
                                $raw = self::getYouTobeImages($id);
                                if (count($raw)) {
                                    $rawData['raw'] = $raw;
                                    self::$sources['youtube'][$id] = $rawData;

                                    if ($isRaw) {
                                        $result = $rawData;
                                    } else {
                                        $result = self::getSimpleYoutubeData($raw);
                                    }
                                }
                                break;
                            case 'vimeo':
                                $raw = self::getVimeoImages($id);
                                if (count($raw)) {
                                    $rawData['raw'] = $raw[0];
                                    self::$sources['vimeo'][$id] = $rawData;

                                    if ($isRaw) {
                                        $result = $rawData;
                                    } else {
                                        $result = self::getSimpleVimeoData($rawData['raw']);
                                    }
                                }
                                break;
                        }
                    }
                }
            }

            return $result;
        }
    }
}
