# handles database and plaintext encryption, decryption, salt generation, all things encryption + hashing
import argon2
import base64
from cryptography.fernet import Fernet
import os

# admin specific functions
def hash_admin_creds(admin_password):
    PH = argon2.PasswordHasher()
    hash = PH.hash(admin_password)
    return hash

def verify_admin(admin_hash, input_password):
    PH = argon2.PasswordHasher()
    return PH.verify(admin_hash, input_password)

# encryption dependencies - these return byte-like object for en/decryption use, or to be decoded and stored in desired location
def generate_salt ():
    salt = os.urandom(16)
    base_64_salt = base64.b64encode(salt)
    return base_64_salt 

def derive_key(admin_pwrd, salt):
    secret = admin_pwrd.encode("utf-8")
    key = argon2.low_level.hash_secret_raw(secret, salt, 3, 65536, 4, 32, argon2.low_level.Type.ID)
    base_64_key = base64.urlsafe_b64encode(key)
    return base_64_key

# database en/decryption fuctions - all en/decryption functions take decoded bytes, so they have to encode them before encryption
def encrypt(key, plain):
    plain_bytes = plain.encode("utf-8")
    f = Fernet(key)
    ciphertoken = f.encrypt(plain_bytes)
    return ciphertoken

def decrypt(key, cipher_token):
    cipher_token.encode("utf-8")
    f = Fernet(key)
    plain = f.decrypt(cipher_token)
    return plain
