# -*- coding: utf-8 -*-
#------------------------------------------------------------
# smytvshow
# HDLOAD server connector
# http://smystero.dlinkddns.org/smytvwhow/
# Adapted from
# ------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector for hdload.org
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
# by DrZ3r0
# ------------------------------------------------------------

import re

from core import scrapertools
from xbmcutils import logger

SERVER_NAME = "[HDLoad]"
SERVER_ID = "hdload"


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

    found = set()

    url_list = []

    patron = '//(?:www.)?hdload.info/embed-([0-9a-zA-Z]+)'
    matches = re.compile(patron).findall(data)

    for match in matches:
        url = 'http://hdload.info/embed-%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:
        data = scrapertools.cache_page(page_url)

        for url in re.findall(r'sources:\s*\[\{file:"([^"]+)",', data, re.DOTALL):
            video_urls.append([url[-4:], url])

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

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


