from os import getenv
from jose import jwt
from datetime import datetime, timedelta


def get_jwt_json(jwt_token, secret):
    return jwt.decode(jwt_token, secret, algorithms=["HS256"])


def set_jwt_json(jo, secret):
    return jwt.encode(jo, secret, algorithm="HS256")


def verify_login_token(login_token, shared_secret):
    try:
        if login_token == "":
            raise Exception("Blank")

        # jo = decrypt(login_token, ss)
        # if expired:
        #     raise Exception('Expired')
        #
        #
        # new_login_token = encrypt(login_token, ss)
        new_login_token = login_token
        return new_login_token
    except:
        return "Invalid"


def valid_api_key(key_name, request):
    header_api_key = request.headers.get(key_name, "noHeaderKey")
    env_api_key = getenv(key_name)

    if not env_api_key:
        return False

    return header_api_key == env_api_key


def authorize_api_to_api(request, api_key):

    if not valid_api_key(api_key, request):
        return False
    return True


def authentication_not_needed(
    request, services=["/", "/Version", "/docs", "/openapi.json", "/SystemStats", "/ResetMemoryTrap", "/MemoryTrap", "/SetLogLevel"]
):
    return request.url.path in services
