# -*- coding: utf-8 -*-
import HTMLParser
import json
import logging
import os
import re
import requests
import ssl
import sys
import urllib
import urllib2
import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin


def get_cloud(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.5',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Origin': 'https://cloudvideo.tv',
        'Connection': 'keep-alive',
        'Referer': url,
        'Upgrade-Insecure-Requests': '1',
        'TE': 'Trailers',
    }
    x = requests.get(url, headers=headers).content
    regex = 'name="op" value="(.+?)"'
    op = re.compile(regex).findall(x)[0]

    # regex = r'''method="POST" action=['"](.+?)['"]'''
    # plink = re.compile(regex).findall(x)[0]

    regex = 'name="usr_login" value="(.+?)"'
    usr_login = re.compile(regex).findall(x)[0]

    regex = 'name="id" value="(.+?)"'
    id_code = re.compile(regex).findall(x)[0]

    regex = 'name="fname" value="(.+?)"'
    fname = re.compile(regex).findall(x)[0]

    regex = 'name="referer" value=(.+?)"'
    referer = re.compile(regex).findall(x)[0]

    regex = 'name="hash" value="(.+?)"'
    hash_code = re.compile(regex).findall(x)[0]

    data = {
        'op': op,
        'usr_login': usr_login,
        'id': id_code,
        'fname': fname,
        'referer': referer.replace('"', ''),
        'hash': hash_code,
        'imhuman': 'Proceed to video'
    }

    response = requests.post(url, headers=headers, data=data).content
    # print response
    import jsunpack
    xbmc.log('RESPONSE: {}'.format(str(response)))
    if jsunpack.detect(response):
        response = jsunpack.unpack(response)
    print response
    regex = 'src:"(.+?)"'
    m = re.compile(regex).findall(response)[0]
    print m + '|Referer={}'.format(url)

get_cloud('https://cloudvideo.tv/9tucxwyz7mxd')