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

import re

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

SERVER_NAME = "[VidZI]"
SERVER_ID = "vidzi"


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

    found = set()

    url_list = []

    patron = 'vidzi.tv/([A-Za-z0-9]+)'
    matches = re.compile(patron, re.DOTALL).findall(data)

    for match in matches:
        url = "http://vidzi.tv/%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)
        flv = c.get_match(data, ',\{.*?file:[^"]+"([^"]+)".*?\}')
        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
