# -*- coding: utf-8 -*-
#------------------------------------------------------------
# smytvshow
# GOOGLEVIDEO server connector
# http://smystero.dlinkddns.org/smytvwhow/
#------------------------------------------------------------

import re

from core import scrapertools, common as c
from xbmcutils import logger

SERVER_NAME = "[GoogleVideo]"
SERVER_ID = "googlevideo"


def find_videos(data):
    logger.debug("start...")

    found = set()

    url_list = []

    #<a href="http://www.nowvideo.eu/video/3695bce6e6288" target="_blank">1° Tempo</a>
    patron = 'http://video.google.com/googleplayer.swf.*?docid=([0-9]+)'
    matches = re.compile(patron, re.DOTALL).findall(data)

    for match in matches:
        if match.count("&") > 0:
            first = match.find("&")
            url = match[:first]
        else:
            url = match
        if url not in found:
            url_list.append([SERVER_ID, SERVER_NAME, url, match[0]])
            found.add(url)

    logger.debug("end...")
    return url_list

def get_video_url(page_url):
    logger.debug("start...")

    video_urls = []

    try:
        if page_url.startswith("http://"):
            url = 'http://www.flashvideodownloader.org/download.php?u='+page_url
        else:
            url = 'http://www.flashvideodownloader.org/download.php?u=http://video.google.com/videoplay?docid='+page_url

        data = scrapertools.cache_page(url)
    
        patron = '</script>.*?<a href="(.*?)" title="Click to Download">'
        matches = re.compile(patron,re.DOTALL).findall(data)
        if len(matches) > 0:
            flv = matches[0]
            video_urls.append([scrapertools.get_filename_from_url(flv)[-4:], flv])

    except:
        logger.error("Probably video [%s] has been removed." % page_url)
        pass

    logger.debug("end...")
    return video_urls

