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

import re

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

SERVER_NAME = "[VideoMega]"
SERVER_ID = "videomega"


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

    found = set()

    url_list = []

    patron = 'videomega.tv/iframe.php\?ref\=([A-Za-z0-9]+)'
    matches = re.compile(patron, re.DOTALL).findall(data)
    for match in matches:
        url = "http://videomega.tv/cdn.php?ref=%s" % match
        if url not in found:
            url_list.append([SERVER_ID, SERVER_NAME, url, match])
            found.add(url)

    patron = 'videomega.tv/\?ref\=([A-Za-z0-9]+)'
    matches = re.compile(patron, re.DOTALL).findall(data)
    for match in matches:
        url = "http://videomega.tv/cdn.php?ref=%s" % match
        if url not in found:
            url_list.append([SERVER_ID, SERVER_NAME, url, match])
            found.add(url)

    patron = 'videomega.tv/view.php\?ref\=([A-Za-z0-9]+)'
    matches = re.compile(patron, re.DOTALL).findall(data)
    for match in matches:
        url = "http://videomega.tv/cdn.php?ref=%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:
        headers = scrapertools.def_headers
        headers.append(['Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'])
        headers.append(['Accept-Encoding', 'gzip, deflate'])
        headers.append(['Accept-Language', 'it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3'])
        headers.append(['Connection', 'keep-alive'])
        headers.append(['Host', 'videomega.tv'])
        headers.append(['Referer', page_url])

        data = scrapertools.cache_page(page_url, headers=headers)
        patron = "(eval.function.p,a,c,k,e,.*?)\s*</script>"
        packed = c.find_single_match(data,patron)
        if data != '':
            unpacked = jsunpack.unpack(packed)
            patron = '"src"\s*,\s*"([^"]+)'
            flv = c.find_single_match(unpacked, patron)
            title = flv[-4:]
            flv = "%s|Referer=%s" % (flv,  page_url)
            video_urls.append([title, flv])

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

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