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

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), }

TMDB_API_KEY = '2e7dc11b26c0a5d1621ed93dc4dfefdc'
TMDB_API_URL = 'https://api.themoviedb.org/3'
TMDB_IMG_URL = 'https://media.themoviedb.org/t/p/w500'
TMDB_WEB_URL = 'https://www.themoviedb.org/movie'

LANG_MAP = {
    'en': 'angielski', 'fr': 'francuski', 'de': 'niemiecki', 'es': 'hiszpański',
    'it': 'włoski', 'pl': 'polski', 'ru': 'rosyjski', 'ja': 'japoński',
    'ko': 'koreański', 'zh': 'chiński', 'pt': 'portugalski', 'sv': 'szwedzki',
    'da': 'duński', 'no': 'norweski', 'fi': 'fiński', 'nl': 'holenderski',
    'cs': 'czeski', 'sk': 'słowacki', 'hu': 'węgierski', 'ro': 'rumuński',
    'tr': 'turecki', 'ar': 'arabski', 'hi': 'hindi', 'th': 'tajski',
    'uk': 'ukraiński', 'el': 'grecki', 'he': 'hebrajski', 'id': 'indonezyjski',
}


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


def _api_get(path, params=None):
    p = {'api_key': TMDB_API_KEY, 'language': 'pl-PL'}
    if params:
        p.update(params)
    url = '%s%s?%s' % (TMDB_API_URL, path, urlencode(p))
    req = request.Request(url, None, headers)
    try:
        response = request.urlopen(req, timeout=10)
        data = json.loads(response.read())
        response.close()
        return data
    except Exception as e:
        return None

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 = []
    params = {'query': item['title_cln']}
    if item.get('year'):
        params['year'] = item['year']
    data = _api_get('/search/movie', params)
    if not data or 'results' not in data:
        if par == 0:
            return items
        return item

    for r in data['results']:
        year = r.get('release_date', '')[:4]
        poster = r.get('poster_path')
        icon = TMDB_IMG_URL + poster if poster else ''
        id_tmdb = str(r['id'])
        items.append({
            'id_tmdb': id_tmdb,
            'icon': icon,
            'url_film': '%s/%s?language=pl-PL' % (TMDB_WEB_URL, id_tmdb),
            'title_film': r.get('title', ''),
            'year': year,
            'plot': r.get('overview', ''),
        })
    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'] = ''
                item['savelvl'] = 4
                break
        return item

def get_tmdb_details(item, savelvl):
    id_tmdb = item.get('id_tmdb', '')
    if not id_tmdb:
        url = item.get('url_film', '')
        m = re.search(r'movie/(\d+)', url)
        id_tmdb = m.group(1) if m else ''
    if not id_tmdb:
        return item
    data = _api_get('/movie/%s' % id_tmdb)
    if not data:
        return item
    title_u = data.get('title', item.get('title_stream', ''))
    poster = data.get('poster_path')
    rd = data.get('release_date', '')
    va = data.get('vote_average', 0)
    genres = ', '.join(g['name'] for g in data.get('genres', []))
    lang_code = data.get('original_language', '')
    item['plot'] = data.get('overview', '')
    item['id_tmdb'] = str(data['id'])
    item['title_stream'] = title_u
    item['title_cln'] = title_u
    item['title_org'] = data.get('original_title', title_u)
    item['lang_org'] = LANG_MAP.get(lang_code, lang_code)
    item['icon'] = TMDB_IMG_URL + poster if poster else item.get('icon', '')
    if rd:
        item['year'] = rd[:4]
    item['rating'] = str(round(va, 1)) if va else '0.0'
    item['genres'] = genres
    item['url_film'] = '%s/%s?language=pl-PL' % (TMDB_WEB_URL, id_tmdb)
    if savelvl == 4:
        savelvl = 5
    item['savelvl'] = savelvl
    return item
