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

import re
import urllib

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


SERVER_NAME = "[JunkyVideo]"
SERVER_ID = "junkyvideo"


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

    found = set()

    url_list = []

    #http://www.junkyvideo.com/r5z9g1kwg9jt
    patron = 'junkyvideo.com/([A-Za-z0-9]+).htm'
    matches = re.compile(patron, re.DOTALL).findall(data)

    for match in matches:
        url = "http://www.junkyvideo.com/%s.htm" % 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)

        hash1 = c.find_single_match(data, 'name="hash" value="([^<]+)"')
        idd = c.find_single_match(data,'name="id" value="([^<]+)"')

        import time
        time.sleep(6)

        params = {'op': 'download1', 'usr_login': '', 'id': idd, 'fname': '', 'referer': '', 'hash': hash1}
        query = urllib.urlencode(params)

        page = scrapertools.cache_page(page_url,post=query)
        page = page.split('file: "')

        flv = page[1].split('"')[0]
        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
