# -*- coding: utf-8 -*-
from django.db import transaction
from django.db.utils import IntegrityError


def create_texts_for_survey(sender, instance, created, **kwargs):
    if created:
        instance.create_texts()


def set_question_slug(sender, instance, created, **kwargs):
    if instance.param_slug in ['', None]:
        set_unique_question_slug(instance)


def set_unique_question_slug(question, next_counter=0):
    from events.surveyme.models import SurveyQuestion

    while True:
        with transaction.atomic():
            question.param_slug = question.generate_next_slug(next_counter=next_counter)
            try:
                SurveyQuestion.objects.filter(id=question.id).update(param_slug=question.param_slug)
                return
            except IntegrityError:
                next_counter += 1


def set_question_data_source_params(sender, instance, created, **kwargs):
    from events.surveyme.models import SurveyQuestion

    if (
        instance.answer_type.slug == 'answer_choices' and
        instance.param_data_source == 'survey_question_choice' and
        instance.param_data_source_params is None
    ):
        SurveyQuestion.objects.filter(id=instance.id).update(
            param_data_source_params={
                'filters': [
                    {
                        'filter': {
                            'name': 'question'
                        },
                        'type': 'specified_value',
                        'value': instance.id
                    }
                ]
            }
        )


def set_question_param_widget_by_data_source(sender, instance, **kwargs):
    if instance.param_data_source == 'survey_question_matrix_choice':
        instance.param_widget = 'matrix'


def set_survey_question_choice_default_slug(sender, instance, created, **kwargs):
    from events.surveyme.models import SurveyQuestionChoice

    if created and not instance.slug:
        SurveyQuestionChoice.objects.db_manager('default').filter(pk=instance.pk).update(slug=str(instance.pk))


def create_survey_tickets(sender, instance, created, **kwargs):
    from events.surveyme.utils import check_survey_tickets_count_consistency

    check_survey_tickets_count_consistency(instance)


def reset_auto_publish_statuses_if_needed(sender, instance, **kwargs):
    # todo: test me
    if instance.datetime_auto_open is None and instance.datetime_auto_close is None:
        instance.auto_control_publication_status = False


def create_profile_survey_answer_counter(sender, instance, created, **kwargs):
    from events.countme.models import AnswerCount
    if created:
        AnswerCount.objects.create(survey=instance)
