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

from dnscms.utils import slugify

SLUGGED_SNIPPETS = {"events.EventOrganizer", "events.EventCategory"}


@receiver(pre_save)
def normalize_slug(sender, instance, **kwargs):
    label = f"{sender._meta.app_label}.{sender.__name__}"
    if isinstance(instance, Page) or label in SLUGGED_SNIPPETS:
        if getattr(instance, "slug", None):
            instance.slug = slugify(instance.slug)
