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

import re

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

SERVER_NAME = "[Novamov]"
SERVER_ID = "novamov"


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 = 'novamov.com/video/([a-z0-9]{13})'
    matches = re.compile(patron, re.DOTALL).findall(data)

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

    patron = 'http://embed.novamov.com/embed.php.*?v=([a-z0-9]{13})'
    matches = re.compile(patron, re.DOTALL).findall(data)

    for match in matches:
        url = "http://www.novamov.com/video/%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:
        video_id = c.get_match(page_url, "http://www.novamov.com/video/([a-z0-9]+)")

        data = scrapertools.cache_page(page_url)

        data = unwise.unwise_process(data)

        file_key = unwise.resolve_var(data, "flashvars.filekey")

        #get stream url from api
        url = 'http://www.novamov.com/api/player.api.php?key=%s&file=%s' % (file_key, video_id)
        data = scrapertools.cache_page(url)

        flv = c.get_match(data,'url=(.+?)&title')
        #stream_url = urllib.unquote(r.group(1))
        video_urls.append([scrapertools.get_filename_from_url(flv)[-4:], flv])

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

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