import json

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from model_utils.models import TimeStampedModel


class OEBSLog(TimeStampedModel):
    """
    Логи важных запросов в OEBS
    """
    object_id = models.IntegerField()
    content_type = models.ForeignKey(
        to=ContentType,
        on_delete=models.CASCADE,
    )
    related_object = GenericForeignKey()

    action = models.CharField(max_length=255, blank=True)

    raw_related_data = models.TextField(default='{}')
    raw_oebs_data = models.TextField(default='{}')

    @property
    def related_data(self):
        return json.loads(self.raw_related_data)

    @related_data.setter
    def related_data(self, value):
        self.raw_related_data = json.dumps(value)

    @property
    def oebs_data(self):
        return json.loads(self.raw_oebs_data)

    @oebs_data.setter
    def oebs_data(self, value):
        self.raw_oebs_data = json.dumps(value)

    @classmethod
    def log(cls, related_object, related_data, oebs_data, action=''):
        log_object = cls(
            action=action,
        )
        log_object.related_object = related_object
        log_object.related_data = related_data
        log_object.oebs_data = oebs_data
        log_object.save()

        return log_object

    def __str__(self):
        return 'OEBS Log #%s' % self.id

    class Meta:
        verbose_name = 'лог OEBS'
        verbose_name_plural = 'логи OEBS'
