# Path: poetry/apps/corpus/models.py
# class Poem(Model):
#     text = TextField("Текст", blank=False)
#     name = CharField("Нвзвание стихотворения", max_length=50, blank=True)
#     author = CharField("Автор", max_length=50, blank=False)
#     date_from = IntegerField("Дата написания - первый год", blank=True, null=True)
#     date_to = IntegerField("Дата написания - второй год", blank=True, null=True)
#     themes = ManyToManyField(Theme, verbose_name="Темы", related_name="poems", blank=True)
#     is_restricted = BooleanField("Стихи с ограниченным доступом", default=False)
#     is_standard = BooleanField("Эталонные (проверенные) стихи", default=False)
# 
#     class Meta:
#         verbose_name = "Стихотворение"
#         verbose_name_plural = "Стихотворения"
#         permissions = (
#             ("can_view_restricted_poems", "Can view restricted poems"),
#         )
# 
#     def __str__(self):
#         return 'Стихотворение: ' + self.get_name() + ", " + str(self.author)
# 
#     def get_name(self):
#         name = self.name
#         if name == "":
#             name = self.text.strip().split("\n")[0]
#             i = len(name) - 1
#             while i > 0 and not name[i].isalpha():
#                 i -= 1
#             name = name[:i+1]
#         return name
# 
#     def get_name_short(self):
#         name = self.__clean_name(self.name)
#         if name == "":
#             name = self.__get_name_form_text()
#         return name[:64].replace(" ", "")
# 
#     def __get_name_form_text(self):
#         name = ""
#         line_number = 0
#         while name == "":
#             name = self.text.strip().split("\n")[line_number]
#             i = len(name) - 1
#             while i > 0 and not name[i].isalpha():
#                 i -= 1
#             name = name[:i+1]
#             name = self.__clean_name(name)
#             line_number += 1
#         return name
# 
#     def __clean_name(self, name):
#         new_name = ""
#         for ch in name:
#             if ch.isalpha() or ch.isalnum() or ch == " ":
#                 new_name += ch
#         return new_name.strip()
# 
#     def count_lines(self):
#         return len(self.text.rstrip().split("\n"))
# 
#     def count_automatic_errors(self):
#         for markup in self.markups.all():
#             if "Automatic" in markup.author:
#                 return markup.get_automatic_additional().get_metre_errors_count()
# 
#     def get_absolute_url(self):
#         if len(self.markups.all()) != 0:
#             return self.markups.all()[0].get_absolute_url()
#         return reverse("corpus:poems")
# 
#     def get_automatic_markup(self):
#         for markup in self.markups.all():
#             if "Automatic" in markup.author:
#                 return markup
#         return None
# 
#     def count_manual_markups(self):
#         return sum([int(markup.markup_version.name == "Manual") for markup in self.markups.all()])


from django.forms import ModelForm
from django.shortcuts import get_object_or_404
from poetry.apps.corpus.models import Poem


class OverwriteOnlyModelFormMixin(object):
    """
    Delete POST keys that were not actually found in the POST dict
    to prevent accidental overwriting of fields due to missing POST data.
    Mixin для поддержки перезаписи полей. Без него незаполенные поля считаются пустыми.
    """
    def __init__(self, *args, **kwargs):
        super(OverwriteOnlyModelFormMixin, self).__init__(*args, **kwargs)
        for key in self.fields.keys():
            self.fields[key].required = False

    def clean(self):
        cleaned_data = super(OverwriteOnlyModelFormMixin, self).clean()
        # Записываем в data новые поля
        data = {}
        for field in cleaned_data.keys():
            if field in self.data:
                data[field] = cleaned_data[field]
        # Запоминаем новые поля
        obj = get_object_or_404(self._meta.model, pk=self.instance.pk)
        # Достаём старые поля и обновляем их
        model_data = obj.__dict__
        model_data.update(data)
        return model_data


class PoemForm(OverwriteOnlyModelFormMixin, ModelForm):
    class Meta:

# Path: poetry/apps/corpus/models.py
# class Poem(Model):
#     text = TextField("Текст", blank=False)
#     name = CharField("Нвзвание стихотворения", max_length=50, blank=True)
#     author = CharField("Автор", max_length=50, blank=False)
#     date_from = IntegerField("Дата написания - первый год", blank=True, null=True)
#     date_to = IntegerField("Дата написания - второй год", blank=True, null=True)
#     themes = ManyToManyField(Theme, verbose_name="Темы", related_name="poems", blank=True)
#     is_restricted = BooleanField("Стихи с ограниченным доступом", default=False)
#     is_standard = BooleanField("Эталонные (проверенные) стихи", default=False)
# 
#     class Meta:
#         verbose_name = "Стихотворение"
#         verbose_name_plural = "Стихотворения"
#         permissions = (
#             ("can_view_restricted_poems", "Can view restricted poems"),
#         )
# 
#     def __str__(self):
#         return 'Стихотворение: ' + self.get_name() + ", " + str(self.author)
# 
#     def get_name(self):
#         name = self.name
#         if name == "":
#             name = self.text.strip().split("\n")[0]
#             i = len(name) - 1
#             while i > 0 and not name[i].isalpha():
#                 i -= 1
#             name = name[:i+1]
#         return name
# 
#     def get_name_short(self):
#         name = self.__clean_name(self.name)
#         if name == "":
#             name = self.__get_name_form_text()
#         return name[:64].replace(" ", "")
# 
#     def __get_name_form_text(self):
#         name = ""
#         line_number = 0
#         while name == "":
#             name = self.text.strip().split("\n")[line_number]
#             i = len(name) - 1
#             while i > 0 and not name[i].isalpha():
#                 i -= 1
#             name = name[:i+1]
#             name = self.__clean_name(name)
#             line_number += 1
#         return name
# 
#     def __clean_name(self, name):
#         new_name = ""
#         for ch in name:
#             if ch.isalpha() or ch.isalnum() or ch == " ":
#                 new_name += ch
#         return new_name.strip()
# 
#     def count_lines(self):
#         return len(self.text.rstrip().split("\n"))
# 
#     def count_automatic_errors(self):
#         for markup in self.markups.all():
#             if "Automatic" in markup.author:
#                 return markup.get_automatic_additional().get_metre_errors_count()
# 
#     def get_absolute_url(self):
#         if len(self.markups.all()) != 0:
#             return self.markups.all()[0].get_absolute_url()
#         return reverse("corpus:poems")
# 
#     def get_automatic_markup(self):
#         for markup in self.markups.all():
#             if "Automatic" in markup.author:
#                 return markup
#         return None
# 
#     def count_manual_markups(self):
#         return sum([int(markup.markup_version.name == "Manual") for markup in self.markups.all()])


# Path: poetry/apps/corpus/forms.py
from django.forms import ModelForm
from django.shortcuts import get_object_or_404
from poetry.apps.corpus.models import Poem



class OverwriteOnlyModelFormMixin(object):
    """
    Delete POST keys that were not actually found in the POST dict
    to prevent accidental overwriting of fields due to missing POST data.
    Mixin для поддержки перезаписи полей. Без него незаполенные поля считаются пустыми.
    """
    def __init__(self, *args, **kwargs):
        super(OverwriteOnlyModelFormMixin, self).__init__(*args, **kwargs)
        for key in self.fields.keys():
            self.fields[key].required = False

    def clean(self):
        cleaned_data = super(OverwriteOnlyModelFormMixin, self).clean()
        # Записываем в data новые поля
        data = {}
        for field in cleaned_data.keys():
            if field in self.data:
                data[field] = cleaned_data[field]
        # Запоминаем новые поля
        obj = get_object_or_404(self._meta.model, pk=self.instance.pk)
        # Достаём старые поля и обновляем их
        model_data = obj.__dict__
        model_data.update(data)
        return model_data


class PoemForm(OverwriteOnlyModelFormMixin, ModelForm):
    class Meta:

        model = Poem