
import json
import re
from urllib import request
from urllib.parse import quote_plus

import xbmc
import xbmcgui
from resources.lib import common, PhantomCommon
from resources.lib import db

cm = PhantomCommon.common()
cnt = common.count()

headers = {'User-Agent': db.readParam(9), }


def log(msg): xbmc.log('===metadata=== ' +msg, level=xbmc.LOGINFO)

def getMeta(items):
    try:
        idlist = []
        for item in items:
            idlist.append(item['id_stream'])
        idlist = str(idlist)
        exec(db.getQuery(4))
        data = re.compile('ids=(.*?),items=(.*?)koniec_meta', flags=re.S).findall(locals()['response'])
        ids = json.loads(data[0][0]) if data else ''
        infos = json.loads(data[0][1]) if data else ''
        dp = xbmcgui.DialogProgressBG()
        dp.create('', '')
        itemslen = len(items)
        for i in range(itemslen):
            id_stream = items[i]['id_stream']
            if id_stream in ids:
                dursec = items[i]['dursec']
                idx = ids.index(id_stream)
                items[i] = infos[idx]
                items[i]['dursec'] = dursec
            elif items[i]['dursec'] >= 3600:
                dp.update(int(i * 100 / itemslen), str(i + 1) + '/' + str(itemslen),
                          items[i]['title_stream'].encode("utf-8"))
                info = tmdb_search(items[i], 1)
                watchlvl = 0
                res_play = ''
                owner = ''
                info['checksum'] = cnt.checkSum(info)
                exec(db.getQuery(8))
                items[i] = info
        dp.close()
        return items
    except Exception as e:
        pass

def tmdb_search(item, par):
    items = []
    search_url = 'https://www.themoviedb.org/search/movie?query=%s&language=pl-PL' % quote_plus(
        item['title_cln'])
    link = getLink(search_url)
    results = re.compile('data-media-type="movie"(.*?)<div id=', re.DOTALL).findall(link)

    for result in results:
        url_film = re.search('/movie/(.*?)"', result)
        icon = re.search('1x, (.*?) 2x', result)
        plot = re.search('<p>(.*?)<', result)
        plot = common.htmlSpecialChars(plot.group(1)) if plot else ''
        title = re.search('alt="(.*?)"', result)
        syear = re.search('release_date">(.*?)<', result)
        year = syear.group(1)[-4:] if syear else ''
        if icon:
            icon = icon.group(1).replace('w188_and_h282_bestv2', 'w500')
            items.append({'id_tmdb': url_film.group(1).split("-")[0], 'icon': icon,
                          'url_film': 'https://www.themoviedb.org/movie/' + url_film.group(1),
                          'title_film': common.htmlSpecialChars(title.group(1)), 'year': year, 'plot': plot})
    if par == 0:
        return items
    elif par == 1:
        counter = len(items)
        for pitem in items:
            title_u = pitem['title_film']
            if counter == 1 or item['year'] == pitem['year']:
                item['id_tmdb'] = pitem['id_tmdb']
                item['url_film'] = pitem['url_film']
                item['title_stream'] = title_u
                item['title_cln'] = title_u
                item['year'] = pitem['year']
                item['icon'] = pitem['icon']
                item['plot'] = pitem['plot']
                item['rating'] = ''  ##pitem['rating']
                item['savelvl'] = 4
                break
        return item


def get_tmdb_details(item, savelvl):
    url = item.get('url_film')
    link = getLink(url)
    id_tmdb = re.search('movie/(\d+)(?:-.*)?', url)
    title = re.search('og:title" content="(.*?)"', link)
    title_u = common.htmlSpecialChars(title.group(1))
    title_org = re.search('Oryginalny tytuł</strong> (.*?)<', link)
    year = re.search('<title>(.*?) \((\d{4})\)', link)
    lang_org = re.search('Oryginalny język</bdi></strong> (.*?)<', link)
    icon = re.search('og:image" content="(.*?)"', link)
    plot = re.compile('"overview".*?p>(.*?)<', re.DOTALL).findall(link)
    rating = re.search('data-percent="(.*?)"', link)
    rt = rating.group(1)
    genres = str(re.compile('genre/.*?">(.*?)<').findall(link)).replace('[', '').replace(']', '').replace("'", "")
    item['plot'] = common.htmlSpecialChars(plot[0])
    item['id_tmdb'] = id_tmdb.group(1)
    item['title_stream'] = title_u.rstrip()
    item['title_cln'] = title_u.rstrip()
    item['title_org'] = common.htmlSpecialChars(title_org.group(1)) if title_org else item[
        'title_stream']
    item['lang_org'] = common.htmlSpecialChars(lang_org.group(1)) if lang_org else ''
    item['icon'] = icon.group(1)
    if year:
        item['year'] = year.group(2)
    item['rating'] = rt[0] + '.' + rt[1] if len(rt) == 2 else '0.0'
    item['genres'] = genres.replace('\\xc5\\x82', 'ł')
    if savelvl == 4:
        savelvl = 5
    item['savelvl'] = savelvl
    return item


def getLink(url):
    req = request.Request(url, None, headers)
    try:
        response = request.urlopen(req, timeout=10)
        link = response.read()
        response.close()
    except:
        link = ''
    return link.decode("utf-8")
