from django.db import models
from django.utils import translation
from django.utils.translation import gettext_lazy as _

class XFieldList(list):
    """ List for field names.
    Changes "*_" to specific field names for the current language,
    i.e.
    "sort_order" => "sort_order"
    "title_" => "title", "title_de", or "title_es"
    "__str__" => "__str__"
    """
    def __init__(self, sequence=[]):
        self.sequence = sequence
    def __iter__(self):
        return iter(self._get_list())
    def __getitem__(self, k):
        return self._get_list()[k]
    def __nonzero__(self):
        return bool(self.sequence)
    def __len__(self):
        return len(self.sequence)
    def __str__(self):
        return str(self._get_list())
    def __repr__(self):
        return repr(self._get_list())
    def _get_list(self):
        language = translation.get_language()[:2]
        result = []
        for item in self.sequence:
            if item[:1]=="-":
                order = "-"
                item = item[1:]
            else:
                order = ""
            if item[:2] == "__" or item[-1:] != "_":
                result.append(order + item)
            else:
                if language == "en":
                    result.append(order + item[:-1])
                else:
                    result.append(order + item + language)
        return result

class TranslatableContent(models.Model):
    title = models.CharField(_("Title"), maxlength=255)
    title_de = models.CharField(_("Title (DE)"), maxlength=255, blank=True)
    title_lt = models.CharField(_("Title (LT)"), maxlength=255, blank=True)
    content = models.TextField(_("Content"))
    content_de = models.TextField(_("Content (DE)"), blank=True)
    content_lt = models.TextField(_("Content (LT)"), blank=True)
    is_published = models.BooleanField(_("Published"))
    class Admin:
        list_display = XFieldList(['title_', 'content_', 'is_published'])
    class Meta:
        verbose_name = _("translatable content")
        verbose_name_plural = _("translatable content")
        ordering = XFieldList(['title_', 'is_published'])
    def __str__(self):
        return self.get_title()
    def get_title(self, language=None):
        return getattr(self, "title_%s" % (language or translation.get_language()[:2]), "") or self.title
    def get_content(self, language=None):
        return getattr(self, "content_%s" % (language or translation.get_language()[:2]), "") or self.content