from django.db import models

from fwd_api.utils.crypto import sds_db_encryptor


class EncryptedCharField(models.CharField):
    description = "Encrypted sin value"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        return name, path, args, kwargs

    def get_prep_value(self, value):
        # encrypt data with your own function
        if value is None:
            return value
        return sds_db_encryptor.encrypt(value)

    def from_db_value(self, value, expression, connection):
        if value is None:
            return value
        # decrypt data with your own function
        return sds_db_encryptor.decrypt(value)

    def to_python(self, value):
        # check if is instance of this type return value
        if value is None:
            return value
        # decrypt data with your own function
        return sds_db_encryptor.decode_data(value)
