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

import re

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

SERVER_NAME = "[VidHappy]"
SERVER_ID = "vidhappy"


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

    found = set()

    url_list = []

    #<a href="http://www.nowvideo.eu/video/3695bce6e6288" target="_blank">1° Tempo</a>
    patron = '(vidhappy.com/[a-z0-9]+)'
    matches = re.compile(patron, re.DOTALL).findall(data)

    for match in matches:
        url = "http://%s" % match
        if url not in found:
            url_list.append([SERVER_ID, SERVER_NAME, url, match[0]])
            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 = scrapertools.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
        data = scrapertools.cache_page(page_url, post=post, headers=headers)

        rtmpurl=c.get_match(data,'streamer\: "([^"]+)"')
        playpath=c.get_match(data,'file\: "([^"]+)"')
        swfurl=c.get_match(data,'src\: "([^"]+)"')
        pageurl = page_url
        tcurl = rtmpurl

        flv = ("%s playpath=%s swfurl=%s pageUrl=%s tcurl=%s" %(rtmpurl, playpath, swfurl, pageurl, tcurl))
        video_urls.append([file_name[-4:], flv])

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

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