# -*- 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

SERVER_NAME = "[StreamingHD]"
SERVER_ID = "streaminghd"


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

    found = set()

    url_list = []

    patron = 'www.italia-film.co/([^/]+)/'
    matches = re.compile(patron, re.DOTALL).findall(data)
    for match in matches:
        url = "http://www.italia-film.co/%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 = []
    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', 'www.italia-film.co'])
    headers.append(['Referer', page_url])
    data = scrapertools.cache_page(page_url, headers=headers)
    ref = c.get_match(data, '<script src="//videomega.tv/validatehash.php\?hashkey=([^"]+)"')
    newpage_url = "http://videomega.tv/view.php?ref=%s&width=700&height=460&val=1" % ref
    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(newpage_url, headers=headers)
        flv, title = c.get_match(data, '<source src="([^"]+)"[^"]+"([^"]+)')
        flv = "%s|Referer=%s" % (flv,  newpage_url)

        video_urls.append([title, flv])

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

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