from base64 import b64encode, b64decode
from AesEverywhere import aes256
import secrets


class OBACipher:
    def __init__(self, encrptyion_secret_key):
        """
        Initializes One Bridge Admin Cipher with encrptyion_secret_key.

        Parameters
        ----------
        encrptyion_secret_key
            OBACipher encryption secret key.

        """
        self.encrptyion_secret_key = encrptyion_secret_key

    def generate_keys(self):
        """
        Generates OneBridge Admin Authorization token and encrypted secret key.

        Returns
        -------
        string
              Admin authorization token.

        string
              Encrypted secret key to be stored in database.

        """

        # generate authentication token
        auth_token = secrets.token_hex(256)

        # generate admin secret key
        admin_secret_key = secrets.token_urlsafe(256)

        # encrypt admin secret key
        encrypted_bytes = aes256.encrypt(admin_secret_key, self.encrptyion_secret_key)

        # encode generated bytes
        base64_encoded_string = b64encode(encrypted_bytes).decode("utf-8")

        return (auth_token, base64_encoded_string)

    def decrypt(self, encrypted_secret_key):
        """
        Decrypts encrypted secret key and returns admin_secret_key

        Parameters
        ----------
        encrypted_secret_key
            Encrypted secret key retireived from database.

        Returns
        -------
        string
              Admin secret key.
        """

        base64_decoded_string = b64decode(encrypted_secret_key)

        admin_secret_key = aes256.decrypt(
            base64_decoded_string, self.encrptyion_secret_key
        ).decode()

        return admin_secret_key
