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

import re

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

SERVER_NAME = "[StreaminTo]"
SERVER_ID = "streaminto"


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

    found = set()

    found.add("http://streamin.to/embed-theme.html")
    found.add("http://streamin.to/embed-jquery.html")
    found.add("http://streamin.to/embed-s.html")
    found.add("http://streamin.to/embed-images.html")
    found.add("http://streamin.to/embed-faq.html")
    found.add("http://streamin.to/embed-embed.html")
    found.add("http://streamin.to/embed-ri.html")
    found.add("http://streamin.to/embed-d.html")
    found.add("http://streamin.to/embed-css.html")
    found.add("http://streamin.to/embed-js.html")
    found.add("http://streamin.to/embed-player.html")
    found.add("http://streamin.to/embed-cgi.html")

    url_list = []

    #http://streamin.to/z3nnqbspjyne
    patron = 'streamin.to/([a-z0-9A-Z]+)'
    matches = re.compile(patron,re.DOTALL).findall(data)

    for match in matches:
        url = "http://streamin.to/embed-%s.html" % match
        if url not in found:
            url_list.append([SERVER_ID, SERVER_NAME, url, match])
            found.add(url)

    #http://streamin.to/embed-z3nnqbspjyne.html
    patron  = 'streamin.to/embed-([a-z0-9A-Z]+)'
    matches = re.compile(patron,re.DOTALL).findall(data)

    for match in matches:
        url = "http://streamin.to/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:
        try:
            if not page_url.startswith("http://streamin.to/embed-"):
                video_id = c.get_match(page_url, "streamin.to/([a-z0-9A-Z]+)")
                page_url = "http://streamin.to/embed-"+video_id+".html"
        except:
            logger.error("Video not found")
            return video_urls

        data = scrapertools.cache_page(page_url)

        patron_flv = 'file: "([^"]+)"'
        patron_jpg = 'image: "(http://[^/]+/)'

        try:
            host = c.get_match(data, patron_jpg)
            flv = "%s%s" % (host, c.get_match(data, patron_flv).split("=")[1]+"/v.flv")
        except:
            frm_op = c.get_match(data,'<input type="hidden" name="op" value="([^"]+)"')
            frm_login = ""
            frm_id = c.get_match(data,'<input type="hidden" name="id" value="([^"]+)"')
            frm_name = c.get_match(data,'<input type="hidden" name="fname" value="([^"]+)"')
            frm_referrer = c.get_match(data,'<input type="hidden" name="referer" value="([^"]*)"')
            frm_hash = c.get_match(data,'<input type="hidden" name="hash" value="([^"]*)"')
            frm_human = c.get_match(data,'<input type="submit" name="imhuman".*?value="([^"]+)"').replace(" ","+")

            import time
            time.sleep(10)

            post = "op=%s&usr_login=%s&id=%s&fname=%s&referer=%s&hash=%s&imhuman=%s" % (frm_op, frm_login, frm_id, frm_name, frm_referrer, frm_hash, frm_human)
            headers = scrapertools.def_headers.append(["Referer", page_url])
            data = scrapertools.cache_page( page_url , post=post, headers=headers )

            host = c.get_match(data, patron_jpg)
            flv = "%s%s" % (host, c.get_match(data, patron_flv).split("=")[1]+"/v.flv")

        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
