import locale

import graphene
from graphene import relay
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField

from news.date_helper import month_to_german_string
from news.models import NewsTeaser


class NewsTeaserNode(DjangoObjectType):
    display_date = graphene.String()

    class Meta:
        model = NewsTeaser
        filter_fields = ['date',]
        interfaces = (relay.Node,)

    def resolve_display_date(self, *args, **kwargs):
        # play it safe, locale might not be installed on platform
        try:
            locale.setlocale(locale.LC_TIME, "de_DE")
            return self.date.strftime("%-d. %B %Y")
        except:
            month = month_to_german_string(self.date.month)
            return f'{self.date.day}. {month} {self.date.year}'


class AllNewsTeasersQuery(object):
    news_teasers = DjangoFilterConnectionField(NewsTeaserNode)

    def resolve_news_teasers(self, info, **kwargs):
        return NewsTeaser.objects.all().order_by('order_id')

