# coding: utf-8
from django.db import models
from django.utils.translation import ugettext_lazy as _
from fb.staff.models import Person, GroupDetails
from fb.feedback.models import Feedback

from django.db.models.signals import post_save
from django.db import transaction


class Quizz(models.Model):

    created = models.DateField(auto_now_add=True)
    owner = models.ForeignKey(Person)
    is_published = models.BooleanField(default=True)

    def count_of_answers(self):
        # TODO: переделать. Этот метод испольузется в списковом сериализаторе,
        #  поэтому для каждого объекта Quizz делается +1 запрос в БД
        return PersonAnswer.objects.filter(
            quizz_answer__question__quizz_id=self.pk
        ).values_list('person', 'on_whom').distinct().count()

    class Meta:
        verbose_name_plural = 'Quizzes'


class QuizzGroup(models.Model):

    quizz = models.ForeignKey(Quizz)
    group = models.ForeignKey(GroupDetails, unique=True)
    include_subdepartments = models.BooleanField(default=False)

    class Meta:
        unique_together = ('quizz', 'group')


class QuizzQuestion(models.Model):

    QT_COMPETENCE = 0
    QT_TEXT_FIELD = 1
    QT_TEXT_AREA = 2
    QT_RADIO_BUTTON = 3
    QT_SELECT = 4
    QT_CHECKBOX = 5

    QTE_TEXT = 'text'
    QTE_CHOICE = 'choice'
    QTE_COMPETENCE = 'competence'

    QUESTION_TYPE_ELEMENTS = {
        QT_TEXT_FIELD: QTE_TEXT,
        QT_TEXT_AREA: QTE_TEXT,
        QT_RADIO_BUTTON: QTE_CHOICE,
        QT_SELECT: QTE_CHOICE,
        QT_CHECKBOX: QTE_CHOICE,
        QT_COMPETENCE: QTE_COMPETENCE,
    }

    QUESTION_TYPES = (
        (QT_COMPETENCE, _('competence')),
        (QT_TEXT_FIELD, _('textfield')),
        (QT_TEXT_AREA, _('textarea')),
        (QT_RADIO_BUTTON, _('radiobutton')),
        (QT_SELECT, _('select')),
        (QT_CHECKBOX, _('checkbox')),
    )

    QF_HEAD = 0
    QF_SUBORDINATED = 1
    QF_CUSTOMER = 2
    QF_CONTRACTOR = 3
    QF_COLLEAGUE = 4
    QF_SELF = 5

    QUESTION_FOR = (
        (QF_HEAD, _('head')),
        (QF_SUBORDINATED, _('subordinated')),
        (QF_CUSTOMER, _('customer')),
        (QF_CONTRACTOR, _('contractor')),
        (QF_COLLEAGUE, _('colleague')),
        (QF_SELF, _('SELF')),
    )

    question_type = models.IntegerField(choices=QUESTION_TYPES,
                                        default=QT_COMPETENCE)
    question_for = models.IntegerField(choices=QUESTION_FOR,
                                       default=QF_HEAD)
    quizz = models.ForeignKey(Quizz)
    text = models.TextField(blank=True)
    description = models.TextField(blank=True)
    position = models.IntegerField()

    @classmethod
    def get_question_type_element(cls, question_type):
        return cls.QUESTION_TYPE_ELEMENTS.get(question_type, None)


class QuizzQuestionAnswer(models.Model):

    question = models.ForeignKey(QuizzQuestion)
    text = models.CharField(max_length=255, blank=True)
    is_open = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        if (self.question.question_type != QuizzQuestion.QT_COMPETENCE
            or self.question.quizzquestionanswer_set.count() < 5
            or (self.question.quizzquestionanswer_set.count() == 5 and self.is_open == True)
        ):
            super(QuizzQuestionAnswer, self).save(*args, **kwargs)


class PersonAnswer(models.Model):

    feedback = models.ForeignKey(Feedback)
    person = models.ForeignKey(Person, related_name='answers_from')
    on_whom = models.ForeignKey(Person, related_name='answers_about')
    quizz_answer = models.ForeignKey(QuizzQuestionAnswer)
    text = models.TextField(max_length=255, blank=True)


def create_answers_for_competence_question(sender, instance, created, **kwargs):
    if not created:
        return

    if instance.question_type == QuizzQuestion.QT_COMPETENCE:
        with transaction.atomic():
            QuizzQuestionAnswer.objects.bulk_create([
                QuizzQuestionAnswer(
                    question=instance, text=answer
                ) for answer in ['1', '2', '3', '4', '5']
            ])


def create_answers_for_text_question(sender, instance, created, **kwargs):
    if not created:
        return

    text_question_types = [QuizzQuestion.QT_TEXT_FIELD, QuizzQuestion.QT_TEXT_AREA]
    if instance.question_type in text_question_types:
        QuizzQuestionAnswer.objects.create(question=instance, is_open=True)

post_save.connect(create_answers_for_competence_question, sender=QuizzQuestion)
post_save.connect(create_answers_for_text_question, sender=QuizzQuestion)
