import logging

from django.db.models.signals import pre_save
from django.dispatch import receiver

from correlation.models import Rule
from correlation.services.rules import check_if_only_status_changed

_log = logging.getLogger(__name__)


@receiver(pre_save, sender=Rule)
def rule_pre_save_update(sender, instance, *args, **kwargs):
    """Check if rule is archived and if it is - disable it"""
    if instance.archived:
        instance.status = False
    if instance._state.adding:
        if not instance.sid:
            try:
                instance.sid = Rule.objects.order_by('sid').last().sid + 1
            except AttributeError:
                instance.sid = 1
        instance.status = True
    else:
        if not instance.is_being_parsed and not check_if_only_status_changed(instance):
            instance.rev += 1
