import base64
import hashlib
import hmac

from boss.model import User
from boss_api.shared.response import UserDto
from cryptography.fernet import Fernet


def generate_hmac_md5_hash(
    message: str,
    key: str,
) -> str:

    return hmac.new(
        key=key.encode(),
        msg=message.encode(),  # noqa
        digestmod=hashlib.md5,
    ).hexdigest()


def get_encrypt_key(
    user_id: int,
) -> bytes:

    secret = bytes(str(403841032 + int(user_id)), "UTF-8")
    hlib = hashlib.md5()
    hlib.update(secret)
    return base64.urlsafe_b64encode(hlib.hexdigest().encode("UTF-8"))


def decrypt_data(
    user_id: int,
    encrypted_data: str,
) -> str:

    fernet = Fernet(key=get_encrypt_key(user_id=user_id))
    decrypted_data = fernet.decrypt(token=encrypted_data.encode("UTF-8"))
    return decrypted_data.decode("UTF-8")


def encrypt_data(
    user_id: int,
    data: str,
) -> str:

    fernet = Fernet(key=get_encrypt_key(user_id=user_id))
    encrypted_data = fernet.encrypt(str(data).encode("UTF-8"))
    return encrypted_data.decode("UTF-8")


def convert_user_dto_into_user_response(
    user: User,
) -> UserDto:

    return UserDto(
        user_id=user.user_id,
        level=user.level,
        user_name=user.user_name,
        long_name=user.long_name,
        status=user.status,
        admission_date=user.admission_date,
        termination_date=user.termination_date,
        password=user.password,
        fingerprint_minutiae=user.fingerprint_minutiae,
        nfc_uuid=user.nfc_uuid,
    )
