import logging
from functools import partial

from django.conf import settings
from django.db import models
from django.db.models.signals import post_save, post_delete

from staff.emission.django.emission_master.utils import now_str


logger = logging.getLogger(__name__)


class LogbrokerLog(models.Model):
    ACTION_CHOICES = [
        ('modify', 'modify'),
        ('delete', 'delete'),
    ]

    class Meta:
        verbose_name = 'Incremental log for model changes'
        verbose_name_plural = verbose_name

    data = models.TextField()
    creation_time = models.CharField(max_length=32, default=now_str, db_index=True)

    action = models.CharField(max_length=10, choices=ACTION_CHOICES, default='modify')
    batch_id = models.UUIDField(db_index=True, null=True, blank=True)

    def __str__(self):
        return '%d "%s"' % (self.id, self.data)


class NotSent(models.Model):
    entry = models.ForeignKey(LogbrokerLog, primary_key=True, unique=True)


class Sent(models.Model):
    entry = models.ForeignKey(LogbrokerLog, primary_key=True, unique=True)


def write_log(sender, instance, using, _action, **kwargs):
    from staff.emission.logbroker.controller import controller

    if sender.__qualname__ in settings.LOG_BROKER_MODELS.get(sender.__module__, {}):
        controller.append(obj=instance, action=_action, using=using)
        controller.commit()


post_save.connect(partial(write_log, _action='modify'), weak=False)
post_delete.connect(partial(write_log, _action='delete'), weak=False)
