
import os
import re
import sys

import xbmc
import xbmcaddon
import xbmcvfs
import requests
from resources.lib import db, dialog

my_addon            = xbmcaddon.Addon()
s                   = requests.Session()

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

def getProfile():
    response = getJson(url='https://api.cda.pl/user/me', auth=True)#.json()
    response2 = getJson(url='https://api.cda.pl/user/me/premium', auth=True)#.json()
    login_name = response.get('login',None)
    login_id = response.get('id',None)
    db.setSetting('login_id',str(login_id))

    status = response2.get('status',None)
    if status.get('premium',None) == 'tak':
        wygasa = status.get('wygasa',None)
        stat = 'premium do '+ str(wygasa)
    else:
        stat = 'standard'
    return login_name, stat


def getJson(url,post=None, params=None, auth=None, data=None):
    acc_token = db.getSetting('acc_token')
    headers = {
    'User-Agent':'pl.cda.tv 1.0 (version 1.2.20 build 10619; Android 8.0.0; Unknown sdk_google_atv_x86)',
    'Accept': 'application/vnd.cda.public+json',
    'Host': 'api.cda.pl',}

    if not auth:
        headers.update({'Authorization': 'Basic YmZjMDYyNDAtOTFkZi00MGYzLWFhMjEtZjc4MTBiZjgxYzYyOldFQ3NSQ0VEY0tLZzVHYkxuTHdiZEppMElQakJkSG45dzlTVUhjbjZsR2t2dU9uN2wya1NiZWhmeVZEWEZwR3c'})
    else:
        headers.update({'Authorization': 'Bearer '+acc_token})
    if not post:
        jsdata = s.get(url, headers=headers, params=params, verify=False).json()
    else:
        jsdata = s.post(url, headers=headers, params=params, data=data, verify=False).json()
    return jsdata


def login():
    username = my_addon.getSetting('cda_user')
    password = my_addon.getSetting('cda_pass')
    import hashlib
    import hmac
    import base64

    passw = password.encode('utf-8') if sys.version_info >= (3,0,0) else password
    md5password=hashlib.md5(passw).hexdigest()
    secret = "s01m1Oer5IANoyBXQETzSOLWXgWs01m1Oer5bMg5xrTMMxRZ9Pi4fIPeFgIVRZ9PeXL8mPfXQETZGUAN5StRZ9P"
    if sys.version_info >= (3,0,0):
        secret = secret.encode('utf-8')
        md5password = md5password.encode('utf-8')
    hashedpassword = base64.b64encode(hmac.new(secret, md5password, digestmod=hashlib.sha256).digest())
    if sys.version_info >= (3,0,0):
        hashedpassword = hashedpassword.decode('utf-8')

    hashedpassword = hashedpassword.replace("/","_").replace("+","-").replace("=","")
    params = (
            ('grant_type', 'password'),
            ('login', username),
            ('password', hashedpassword),
            )
    response = getJson(url='https://api.cda.pl/oauth/token', post=True, params=params)#.json()
    tok = response.get('access_token',None)
    if tok:
        db.setSetting('acc_token',tok)
        profil = getProfile()
        return profil
    elif response.get('error',None) == 'invalid_login_or_password':
        dialog.infoDialog('Błąd logowania', 'Sprawdź parametry w ustawieniach')
        return '', ''




