import base64
import calendar
import json
import time
import uuid


def base64UrlEncode(val):
    return base64.urlsafe_b64encode(val.encode()).decode().rstrip("=")


def get_unix_time_in_seconds():
    '''Seconds since the epoch in UTC time'''
    return calendar.timegm(time.gmtime())


def make_device_jwt_base(
    device_client_id: str,
    issuer: str,
) -> dict:
    now = get_unix_time_in_seconds()
    device_token_jwt_claim = {
        'iss': device_client_id,
        'sub': device_client_id,
        'aud': issuer,
        'jti': str(uuid.uuid4()),
        'iat': now,
        'exp': now + 300,
    }
    return device_token_jwt_claim


def device_singing_base(
    sig_content: dict,
    device_client_id: str,
    issuer: str,
    iat: int,
    exp: int,
    alg: str = 'RS256',
    typ: str = 'JWT',
) -> str:
    stringified_header = json.dumps({
        "iss": device_client_id,
        "sub": device_client_id,
        "aud": issuer,
        "jti": str(uuid.uuid4()),
        "iat": iat,
        "exp": exp,
        "alg": alg,
        "typ": typ,
    })
    
    encoded_header = base64UrlEncode(stringified_header)
    encoded_payload = base64UrlEncode(json.dumps(sig_content))
    
    return "{}.{}".format(encoded_header, encoded_payload)