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

import re

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

SERVER_NAME = "[BackIn]"
SERVER_ID = "backin"


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

    found = set()

    url_list = []

    #<a href="http://backin.net/0hmi0bn6sy57">Backin</a>
    patron = 'backin.net/([a-z0-9]+)'
    matches = re.compile(patron, re.DOTALL).findall(data)

    for match in matches:
        url = "http://backin.net/s/generating.php?code=%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 = []

    try:
        video_id = c.get_match(page_url, "code=([a-z0-9]+)")

        headers = scrapertools.def_headers
        headers.append(['Referer', "http://backin.net/%s" % video_id])

        data = scrapertools.cache_page(page_url)

        # <source type="video/mp4" src="http://decepticonh.backin.net:182/d/vfijlghkk2xjfmz2lshnpybqjnlvqn3v2rywamrmqvdemrr4gl2kre4z/Scandal.4x07.Baby.Ha.Fatto.Un.Casino.ITA.DLMux.x264-DpHs.mkv.mp4.mp4.mp4">
        flv = c.get_match(data,'<source type="[^\=]+\="([^"]+)">')
        flv = "%s|Referer=%s" % (flv,  "http://backin.net/stream-%s" % video_id)

        video_urls.append([scrapertools.get_filename_from_url(flv)[-4:], flv])

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

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