# -*- coding: utf-8 -*-
#------------------------------------------------------------
# smytvshow
# VIDTO 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 = "[VidTO]"
SERVER_ID = "vidto"


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

    found = set()

    url_list = []

    #http://vidto.me/uoii2j5wcz0q.html
    patron = 'vidto.me/([a-z0-9]+)'
    matches = re.compile(patron, re.DOTALL).findall(data)

    for match in matches:
        url = "http://vidto.me/%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:
        headers = scrapertools.def_headers
        headers.append(['Referer', page_url])

        data = scrapertools.cache_page(page_url, headers=headers)

        form = c.get_match(data,'<Form[^>]*method="POST"(.*)</.orm>')

        op = c.get_match(form, '<input type="hidden" name="op" value="([^"]+)"')
        usr_login = c.get_match(form, '<input type="hidden" name="usr_login" value="([^"]*)"')
        id = c.get_match(form, '<input type="hidden" name="id" value="([^"]+)"')
        file_name = c.get_match(form, '<input type="hidden" name="fname" value="([^"]+)"')
        referrer = c.get_match(form, '<input type="hidden" name="referer" value="([^"]*)"')
        digest = c.get_match(form, '<input type="[^"]+" name="hash" value="([^"]+)"')

        post = "op="+op+"&usr_login="+usr_login+"&id="+id+"&fname="+file_name+"&referer="+referrer+"&hash="+digest

        import time
        time.sleep(6)

        data = scrapertools.cache_page(page_url, post=post, headers=headers)

        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 = '\{label:"([^"]+)"[^"]+"([^"]+)"\}'
        matches = re.compile(patron, re.DOTALL).findall(unpacked)
        for match in matches:
            video_urls.append([match[0], match[1]])

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

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