
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 1.6 (version 1.2.115 build 16083; Android 9; Samsung SM-J330F)',
    '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"
    secret = secret.encode('utf-8')
    md5password = md5password.encode('utf-8')
    hashedpassword = base64.b64encode(hmac.new(secret, md5password, digestmod=hashlib.sha256).digest())
    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 '', ''




