# -*- coding: utf-8 -*-
from django.conf import settings
from django.utils.translation import ugettext as _
from rest_framework.serializers import (
    BooleanField,
    CharField,
    ChoiceField,
    FloatField,
    IntegerField,
    Serializer,
    SerializerMethodField,
    URLField,
    ValidationError,
)
from events.media.models import Image
from events.media.api_admin.v2.serializers import ImageSerializer
from events.surveyme.dataclasses import (
    SurveyQuiz,
    SurveyQuizItem,
    QUIZ_CALC_METHOD_RANGE,
    QUIZ_CALC_METHOD_SCORES,
)


MAX_URL_LENGTH = 8192
MIN_TIMEOUT_DELAY = 5000  # msec
MAX_TIMEOUT_DELAY = 30000  # msec
DEFAULT_TIMEOUT_DELAY = 10000  # msec
QUIZ_CALC_METHOD_CHOICES = (
    QUIZ_CALC_METHOD_RANGE,
    QUIZ_CALC_METHOD_SCORES,
)
QUIZ_MIN_ITEMS_COUNT = 2


class RedirectSerializer(Serializer):
    enabled = BooleanField(default=False, required=False)
    url = URLField(max_length=MAX_URL_LENGTH, required=False, default='', allow_blank=True)
    auto_redirect = BooleanField(default=False, required=False)
    with_delay = BooleanField(default=False, required=False)
    timeout = IntegerField(min_value=0, max_value=MAX_TIMEOUT_DELAY, default=DEFAULT_TIMEOUT_DELAY, required=False)
    keep_iframe = BooleanField(default=False, required=False)

    def validate(self, data):
        errors = {}
        if data['enabled']:
            if not data.get('url'):
                errors['url'] = URLField.default_error_messages['invalid']
            if settings.IS_BUSINESS_SITE:
                # в b2b авторедирект должен быть вегда выключен
                if data.get('auto_redirect'):
                    data['auto_redirect'] = False
                # в b2b запрещаем далать короткую задержку перед редиректом
                if data.get('timeout', 0) < MIN_TIMEOUT_DELAY:
                    data['timeout'] = MIN_TIMEOUT_DELAY
            if data.get('auto_redirect') and data.get('with_delay'):
                if 'timeout' not in data:
                    errors['timeout'] = IntegerField.default_error_messages['invalid']
            if 'keep_iframe' not in data:
                data['keep_iframe'] = False
        if errors:
            raise ValidationError(errors)
        return data


class FooterSerializer(Serializer):
    enabled = BooleanField(default=True, required=False)

    def validate_enabled(self, value):
        if settings.IS_BUSINESS_SITE:
            return True

        return value


class StatsSerializer(Serializer):
    enabled = BooleanField(default=False, required=False)


class TeaserSerializer(Serializer):
    enabled = BooleanField(default=True, required=False)

    def validate_enabled(self, value):
        if settings.IS_BUSINESS_SITE:
            return True

        return value


class QuizItemSerializer(Serializer):
    title = CharField(max_length=256)
    description = CharField(required=False, max_length=1024, allow_blank=True)
    image_id = IntegerField(required=False, default=None, allow_null=True)
    image = SerializerMethodField()

    def get_image(self, obj):
        try:
            image = Image.objects.get(pk=obj.get('image_id'))
            return ImageSerializer(image).data
        except Image.DoesNotExist:
            pass

    def validate(self, data):
        item = SurveyQuizItem(data)
        if item.image_id is not None:
            if not Image.objects.filter(pk=item.image_id).exists():
                raise ValidationError({'image_id': _('Некорректой код картинки')})
        return data


class QuizSerializer(Serializer):
    show_results = BooleanField(default=False)
    show_correct = BooleanField(default=False)
    calc_method = ChoiceField(choices=QUIZ_CALC_METHOD_CHOICES, default=QUIZ_CALC_METHOD_RANGE)
    pass_scores = FloatField(default=0)
    total_scores = FloatField(read_only=True)
    question_count = IntegerField(source='quiz_question_count', read_only=True)
    items = QuizItemSerializer(many=True, default=[])

    def validate(self, data):
        quiz = SurveyQuiz(data)
        if not quiz.items:
            raise ValidationError({'items': _('Список поддиапазонов не может быть пустым')})
        if quiz.calc_method == QUIZ_CALC_METHOD_SCORES:
            if len(quiz.items) != QUIZ_MIN_ITEMS_COUNT:
                raise ValidationError({'items': _('Список поддиапазонов должен быть равен двум')})
        elif quiz.calc_method == QUIZ_CALC_METHOD_RANGE:
            if len(quiz.items) < QUIZ_MIN_ITEMS_COUNT:
                raise ValidationError({'items': _('Список поддиапазонов должен быть больше или равен двум')})
        if quiz.calc_method == 'scores':
            if quiz.pass_scores is None:
                raise ValidationError({'pass_scores': _('Пороговое значение не может быть null')})
            if quiz.pass_scores < 0:
                raise ValidationError({'pass_scores': _('Пороговое значение должно быть больше ноля')})
            total_scores = self.instance.total_scores or 0.0
            if quiz.pass_scores > total_scores:
                raise ValidationError({'pass_scores': _('Пороговое значение должно быть меньше максимального количества баллов')})
        return data
