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

import re

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

SERVER_NAME = "[FlashX]"
SERVER_ID = "flashx"


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

    found = set()

    url_list = []

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

    for match in matches:
        url = "http://www.flashx.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:
        data = scrapertools.cache_page(page_url)
        frm_url = "http://www.flashx.tv%s" % (c.get_match(data,'<Form method="POST" action=\'([^\']+)\'>'))
        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)
        data = scrapertools.cache_page(frm_url, post=post)

        try:
            packed = c.get_match(data,"(<script type='text/javascript'>eval\(function\(p,a,c,k,e,d\).*?</script>)")
        except:
            packed = c.get_match(data,"(function\(p, a, c, k, e, d\).*?</script>)")
            packed = "<script type='text/javascript'>eval("+packed

        unpacked = unpackerjs.unpack_js(packed)

        patron = '\{file:"([^"]+)"[^"]+"([^"]+)"\}'
        matches = re.compile(patron, re.DOTALL).findall(unpacked)
        for match in matches:
            video_urls.append([match[1], match[0]])

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

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