import base64
import hashlib
from cryptography.fernet import Fernet, InvalidToken
from django.conf import settings
from rest_framework.exceptions import ValidationError
from .security_config import value


def cipher():
    key = value('ACCOUNT_SECURITY_ENCRYPTION_KEY')
    if not key and settings.DEBUG:
        key = base64.urlsafe_b64encode(hashlib.sha256(('ftg-development-only:'+settings.SECRET_KEY).encode()).digest())
    if not key:
        raise ValidationError('Account security encryption key must be configured.')
    try:
        return Fernet(key)
    except (ValueError,TypeError) as exc:
        raise ValidationError('Invalid account security encryption key.') from exc


def encrypt(text):
    return cipher().encrypt(text.encode()).decode()


def decrypt(text):
    try:
        return cipher().decrypt(text.encode()).decode()
    except InvalidToken as exc:
        raise ValidationError('Account encryption key cannot decrypt this credential.') from exc
