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

import re

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

SERVER_NAME = "[SpeedVideo]"
SERVER_ID = "speedvideo"


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

    found = set()
    found.add("http://speedvideo.net/embed")

    url_list = []

    patron = 'speedvideo.net/embed-([A-Z0-9a-z]+)-'
    matches = re.compile(patron).findall(data)

    for match in matches:
        url = "http://speedvideo.net/%s" % match
        if url not in found:
            url_list.append([SERVER_ID, SERVER_NAME, url, match])
            found.add(url)

    patron = 'speedvideo.net/([A-Z0-9a-z]+)'
    matches = re.compile(patron).findall(data)

    for match in matches:
        url = "http://speedvideo.net/%s" % 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:
        data = scrapertools.cache_page(page_url)

        hash1 = c.find_single_match(data, 'name="hash" value="([^<]+)"')
        idd = c.find_single_match(data, 'name="id" value="([^<]+)"')

        import time
        time.sleep(1)

        post = "op=%s&usr_login=%s&id=%s&fname=%s&referer=%s&hash=%s" % ('download1', '', idd, '', '', hash1)
        data = scrapertools.cache_page(page_url, post=post)

        codif = c.find_single_match(data, 'var [a-z]+ = ([0-9]+);')
        link = c.find_single_match(data, 'linkfile ="([^"]+)"')

        numero = int(codif)
        link = jsbase64decode.decode(link, numero)

        video_urls.append([link[-4:],link])

    except Exception as e:
        logger.error("Probably video [%s] has been removed. [%s]" % (page_url, e.message))
        pass

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