from django.db import models
from django.db.models import signals
from admin_ordering.models import OrderableModel
from filebrowser.fields import FileBrowseField
from .utils import PostableModel, PublishableModel

# Create your models here.


class AdditionalPage(PublishableModel):
    published = models.BooleanField('Strona opublikowana', default=False)
    slug = models.SlugField('Link', max_length=255, unique=True, primary_key=True)
    title = models.CharField('Nazwa', max_length=255)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = "Dodatkowa zakładka"
        verbose_name_plural = "Dodatkowe zakładki"


class AdditionalPagePost(PostableModel):
    page = models.ForeignKey(AdditionalPage, on_delete=models.CASCADE, related_name='posts', verbose_name='Strona')
    reverse_href = "post-reverse"

    class Meta(OrderableModel.Meta):
        verbose_name = "Post na stronie"
        verbose_name_plural = "Posty na stronie"


class Button(OrderableModel):
    published = models.BooleanField("Przycisk opublikowany", default=True)
    title = models.CharField("Tekst na przycisku", max_length=50)
    href = models.CharField("Link", max_length=50)
    blank = models.BooleanField("Otwórz w nowej karcie")

    def __str__(self):
        return self.title or "-"

    @property
    def link(self):
        return self.href

    class Meta(OrderableModel.Meta):
        verbose_name = "Przycisk nawigacji (zielony)"
        verbose_name_plural = "Przyciski nawigacji (zielone)"


class UpperButton(OrderableModel):
    published = models.BooleanField("Przycisk opublikowany", default=True)
    title = models.CharField("Tytuł przycisku", max_length=50)
    photo = FileBrowseField(
        "Ikona", directory="gorneprzyciski/", max_length=200, blank=True
    )
    href = models.CharField("Link", max_length=50)
    blank = models.BooleanField("Otwórz w nowej karcie")

    def __str__(self):
        return self.title or "-"

    class Meta(OrderableModel.Meta):
        verbose_name = "Przycisk górny (łabs, atu, itd...)"
        verbose_name_plural = "Przyciski górne (łabs, atu, itd...)"


def create_page_button(sender, instance, created, **kwargs):
    if created:
        Button.objects.create(href=instance.slug, title=instance.title, published=False, blank=False)


signals.post_save.connect(
    create_page_button,
    sender=AdditionalPage,
    weak=False,
    dispatch_uid="models.create_page_button",
)
