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

import re

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

SERVER_NAME = "[FastVideo]"
SERVER_ID = "fastvideo"


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

    found = set()
    found.add("http://www.fastvideo.me/embed-theme.html")
    found.add("http://www.fastvideo.me/embed-jquery.html")
    found.add("http://www.fastvideo.me/embed-s.html")
    found.add("http://www.fastvideo.me/embed-images.html")
    found.add("http://www.fastvideo.me/embed-faq.html")
    found.add("http://www.fastvideo.me/embed-embed.html")
    found.add("http://www.fastvideo.me/embed-ri.html")
    found.add("http://www.fastvideo.me/embed-d.html")
    found.add("http://www.fastvideo.me/embed-css.html")
    found.add("http://www.fastvideo.me/embed-js.html")
    found.add("http://www.fastvideo.me/embed-player.html")
    found.add("http://www.fastvideo.me/embed-cgi.html")

    url_list = []

    patron = "fastvideo.me/([a-z0-9A-Z]+)"
    matches = re.compile(patron,re.DOTALL).findall(data)
    for match in matches:
        url = "http://www.fastvideo.me/embed-%s.html" % match
        if url not in found:
            url_list.append([SERVER_ID, SERVER_NAME, url, match])
            found.add(url)

    patron = "fastvideo.me/embed-([a-z0-9A-Z]+)"
    matches = re.compile(patron,re.DOTALL).findall(data)
    for match in matches:
        url = "http://www.fastvideo.me/embed-%s.html" % match
        if url not in found:
            url_list.append([SERVER_ID, SERVER_NAME, url, match])
            found.add(url)

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


def get_video_url(page_url):
    logger.debug("start...")
    video_urls = []

    try:
        try:
            if not page_url.startswith("http://www.fastvideo.me/embed-"):
                video_id = c.get_match(page_url, "fastvideo.me/([a-z0-9A-Z]+)")
                page_url = "http://www.fastvideo.me/embed-"+video_id+".html"
        except:
            logger.error("Video not found")

        data = scrapertools.cache_page(page_url)

        try:
            packed = c.get_match(data,"(<script type='text/javascript'>eval\(function\(p,a,c,k,e,d\).*?</script>)")
        except:
            packed = c.get_match(data,"(function\(p, a, c, k, e, d\).*?</script>)")
            packed = "<script type='text/javascript'>eval("+packed

        unpacked = unpackerjs.unpack_js(packed)

        patron = 'sources:\[\{file:"([^"]+)"'
        location = c.find_single_match(unpacked,patron)

        video_urls.append([scrapertools.get_filename_from_url(location)[-4:], location])

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

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