import base64
import libnacl

import diderypy.lib.didering as didering

"""
This module provides various key generation and manipulation functions for use with the didery server.  
Keys are generated using the python libnacl library.
"""


def keyToKey64u(key):
    """
    keyToKey64u allows you to convert a key from a byte string to a base64 url-file safe string.

    :param key: 32 byte string
    :return: base64 url-file safe string
    """
    if key is None:
        return None

    return base64.urlsafe_b64encode(key).decode("utf-8")


def key64uToKey(key64u):
    """
    key64uToKey allows you to convert a base64 url-file safe key string to a byte string

    :param key64u: base64 ulr-file safe string
    :return: byte string
    """
    if key64u is None:
        return None

    return base64.urlsafe_b64decode(key64u.encode("utf-8"))


def keyGen(seed=None):
    """
    keyGen generates a url-file safe base64 public private key pair.
    If a seed is not provided libnacl's randombytes() function will
    be used to generate a seed.

    :param seed: The seed value used during key generation.
    :return: url-file safe base64 verifier/public key, signing/private key
    """
    if seed is None:
        seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES)

    vk, sk = libnacl.crypto_sign_seed_keypair(seed)

    did = didering.didGen(vk)

    return keyToKey64u(vk), keyToKey64u(sk), did


def historyGen(seed=None):
    """
    historyGen generates a new key history dictionary and returns the
    history along with all generated keys. If a seed is not provided
    libnacl's randombytes() function will be used to generate a seed.

    :param seed: The seed value used during key generation.
    :return: a history dictionary with an "id", "signer" and "signers" field,
             url-file safe base64 verifier/public key string,
             url-file safe base64 signing/private key,
             url-file safe base64 pre-rotated verifier/public key,
             url-file safe base64 pre-rotated signing/private key
    """
    vk, sk, did = keyGen(seed)
    pre_rotated_vk, pre_rotated_sk, did = keyGen(seed)

    history = {
        "id": didering.didGen64(vk),
        "signer": 0,
        "signers": [
            vk,
            pre_rotated_vk
        ]
    }

    return history, vk, sk, pre_rotated_vk, pre_rotated_sk
