# -*- coding: utf-8 -*-
"""
Monkeypatch для social monkeypatches
На этапе записи в базу потенциально сенситивных данных (например access_token) они должны зашифровываться
При чтении, соответственно, расшифровываться.
"""

from social_django.fields import JSONField, ValidationError
from cryptography.fernet import Fernet
import json


FERNET_KEY = None
with open('/usr/share/overload/overload-social-extradata-fernet-key') as fernet_key_file:
    FERNET_KEY = fernet_key_file.read().strip()

assert FERNET_KEY


def _decrypt(self, data):
    f = Fernet(self.encryption_key)
    return f.decrypt(data)


def _encrypt(self, data):
    f = Fernet(self.encryption_key)
    return f.encrypt(data)


def to_python(self, value):
    """
    Decrypt data from table, convert it's JSON value into python structures, raises
    django.core.exceptions.ValidationError if the data can't be converted.
    Python2 only
    """
    if self.blank and not value:
        return {}
    value = value or '{}'
    try:
        return json.loads(value)
    except ValueError:
        try:
            return json.loads(self._decrypt(str(value)))
        except Exception as err:
            raise ValidationError(str(err))


def get_prep_value(self, value):
    """Convert value to JSON string and encrypts it before save"""
    try:
        return self._encrypt(json.dumps(value))
    except Exception as err:
        raise ValidationError(str(err))


setattr(JSONField, 'encryption_key', FERNET_KEY)
setattr(JSONField, '_decrypt', _decrypt)
setattr(JSONField, '_encrypt', _encrypt)
setattr(JSONField, 'to_python', to_python)
setattr(JSONField, 'get_prep_value', get_prep_value)
