from django.db import models
from django.urls.base import reverse_lazy
from django.utils.safestring import mark_safe
from tinymce.models import HTMLField
from admin_ordering.models import OrderableModel
from core.utils import SingletonModel
from db.help import buttons_help_text

# Create your models here.


class Post(OrderableModel):
    published = models.BooleanField('Wpis opublikowany', default=True)
    show_title = models.BooleanField('Pokaż tytuł', default=True)
    title = models.CharField('Tytuł', default='', blank=True, max_length=250)
    content = HTMLField('Treść', default='', blank=True)
    buttons = models.TextField(
        'Przyciski', default='', blank=True, help_text=buttons_help_text)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title or '(brak tytułu)'

    @property
    def link(self):
        href = reverse_lazy('home-reverse', args=[self.id])
        return mark_safe(f'<a href="{href}" target="_blank">{href}</a>')

    class Meta(OrderableModel.Meta):
        verbose_name = 'Aktualność PodlZBS'
        verbose_name_plural = 'Aktualności PodlZBS'


class GrandPrixW(models.Model):
    published = models.BooleanField('Grand Prix opublikowane', default=True)
    year = models.IntegerField('Rok', primary_key=True, default=1)
    content = HTMLField('Tekst GPW', default='', blank=True)
    buttons = models.TextField(
        'Przyciski', default='', blank=True, help_text=buttons_help_text)
    current = models.BooleanField(
        'Aktualne GP (pokazywane na stronie głównej)', default=False)

    @staticmethod
    def get_current():
        return GrandPrixW.objects.filter(current=True, published=True).first()

    def update(self, *args, **kwargs):
        if self.current is True:
            GrandPrixW.objects.exclude(year=self.year).update(current=False)

    def __str__(self):
        return f'Grand Prix Województwa {self.year}'

    @property
    def link(self):
        href = reverse_lazy('gpw-reverse', args=[self.year])
        return mark_safe(f'<a href="{href}" target="_blank">{href}</a>')

    class Meta:
        verbose_name = 'Grand Prix Województwa'
        verbose_name_plural = 'Grand Prix Województwa'
        ordering = ['-year']
