# coding: utf-8
from __future__ import unicode_literals, absolute_import

from functools import partial

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

from emission.core.exceptions import EmissionImproperlyConfigured
from emission.django.base_models import BaseLog
from emission.django.utils import load_model

from . import settings


class MasterLog(BaseLog):
    pass


if settings.REPLICATED_MODELS:
    def write_log(sender, instance, _action, **kwargs):
        from .controller import controller

        for model_name in settings.REPLICATED_MODELS:
            try:
                model = load_model(model_name)
            except EmissionImproperlyConfigured:
                continue

            if sender == model:
                controller.append(instance, _action)

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