# -*- coding: utf-8 -*-
import re

from django.utils.translation import ugettext_lazy as _
from json import loads as json_loads

from events.surveyme.models import Survey, SurveyQuestion, SurveyTemplate


class ActionSurveyImportList:
    text = _('Форма создана из шаблона «%(name)s»')
    text_import_from_file = _('Форма создана из файла')

    class TemplateSlugNotFound(Exception):
        pass

    def get_template_slug(self, history_entry):
        try:
            data = json_loads(history_entry.request)
            return data['import_from_template']
        except (TypeError, KeyError) as e:
            raise self.TemplateSlugNotFound from e

    def is_digit(self, template_slug):
        if isinstance(template_slug, str):
            return template_slug.isdigit()
        return isinstance(template_slug, int)

    def get_survey_template(self, history_entry):
        template_slug = self.get_template_slug(history_entry)
        if template_slug:
            try:
                if self.is_digit(template_slug):
                    return SurveyTemplate.objects.get(pk=template_slug)
                else:
                    return SurveyTemplate.objects.get(slug=template_slug)
            except SurveyTemplate.DoesNotExist:
                return None

    def get_survey_template_name(self, history_entry):
        survey_template = self.get_survey_template(history_entry)
        if survey_template:
            return survey_template.name
        return '???'

    def get_template(self, history_entry):
        try:
            return self.text % {
                'name': self.get_survey_template_name(history_entry),
            }
        except self.TemplateSlugNotFound:
            return self.text_import_from_file


class ActionSurveyCopy:
    text = _('Форма скопирована из «%(name)s»')

    def get_old_survey(self, history_entry):
        m = re.search(r'/(\d+)/copy/$', history_entry.path)
        if m:
            try:
                return Survey.with_deleted_objects.get(pk=m.group(1))
            except Survey.DoesNotExist:
                return None

    def get_old_survey_name(self, history_entry):
        old_survey = self.get_old_survey(history_entry)
        if old_survey:
            return old_survey.get_name()
        return '???'

    def get_template(self, history_entry):
        return self.text % {
            'name': self.get_old_survey_name(history_entry),
        }


class ActionSimpleText:
    text = None

    def get_template(self, *argc):
        return self.text


class ActionSurveyDetail(ActionSimpleText):
    text = _('Изменены настройки формы')


class ActionSurveyQuiz(ActionSimpleText):
    text = _('Изменены настройки результатов тестов')


class ActionSurveyBan(ActionSimpleText):
    text = _('Изменен статус блокировки формы')


class ActionSurveyList(ActionSimpleText):
    text = _('Создана новая форма')


class ActionSurveyQuestion:
    text = '«%(label)s»'

    def get_template(self, history_entry):
        obj = history_entry.content_object
        format = self.get_format(history_entry)
        return format % {'label': obj.get_label()}

    def get_format(self, history_entry):
        return self.text


class ActionSurveyQuestionList(ActionSurveyQuestion):
    text = _('Создан новый вопрос «%(label)s»')


class ActionSurveyQuestionDetail(ActionSurveyQuestion):
    text_patch = _('Изменен вопрос «%(label)s»')
    text_delete = _('Удален вопрос «%(label)s»')

    def get_format(self, history_entry):
        if history_entry.method == 'PATCH':
            return self.text_patch
        elif history_entry.method == 'DELETE':
            return self.text_delete
        return self.text


class ActionSurveyQuestionRestore(ActionSurveyQuestion):
    text = _('Восстановлен вопрос «%(label)s»')


class ActionSurveyQuestionCopy:
    text = _('Вопрос «%(new_label)s» скопирован из «%(old_label)s»')

    def get_old_question(self, history_entry):
        m = re.search(r'/(\d+)/copy/$', history_entry.path)
        if m:
            try:
                return SurveyQuestion.with_deleted_objects.get(pk=m.group(1))
            except SurveyQuestion.DoesNotExist:
                return None

    def get_old_question_label(self, history_entry):
        old_question = self.get_old_question(history_entry)
        if old_question:
            return old_question.get_label()
        return '???'

    def get_template(self, history_entry):
        question = history_entry.content_object
        return self.text % {
            'new_label': question.get_label(),
            'old_label': self.get_old_question_label(history_entry),
        }


class ActionSurveyQuestionShowConditionNodeSaveWithItemsList(ActionSurveyQuestion):
    text = _('Изменена логика показа вопроса «%(label)s»')


class ActionSurveySubmitConditionNodeSaveWithItemsList(ActionSimpleText):
    text = _('Изменена логика кнопки «Отправить»')


class ActionSurveyTextDetail:
    text = _('Изменен текст для «%(label)s»')

    labels = {
        'successful_submission': _('Событие после отправки'),
        'successful_change': _('Текст после успешного изменения формы'),
        'successful_submission_title': _('Событие после отправки'),
        'save_changes_button': _('Кнопка сохранения изменения формы'),
        'successful_change_title': _('Сообщение после изменения формы'),
        'back_button': _('Кнопка перехода на предыдущую страницу'),
        'next_button': _('Кнопка перехода на следующую страницу'),
        'submit_button': _('Кнопка отправки формы'),
        'redirect_button': _('Кнопка перехода на сайт'),
    }

    def get_template(self, history_entry):
        obj = history_entry.content_object
        return self.text % {'label': self.labels.get(obj.slug)}


class ActionHookSubscriptionNotificationRestartList(ActionSimpleText):
    text = _('Перезапущена интеграция')


class ActionHookSubscriptionNotificationCancelList(ActionSimpleText):
    text = _('Остановлена интеграция')


class ActionSurveyAccess(ActionSimpleText):
    text = _('Изменены настройки доступа')


class ActionSurveyRestore(ActionSimpleText):
    text = _('Форма восстановлена')


ACTIONS = {
    'admin_api_v2:survey-ban': ActionSurveyBan(),
    'admin_api_v2:survey-copy': ActionSurveyCopy(),
    'admin_api_v2:survey-detail': ActionSurveyDetail(),
    'admin_api_v2:survey-import-list': ActionSurveyImportList(),
    'admin_api_v2:survey-import-tracker-list': ActionSurveyImportList(),
    'admin_api_v2:survey-list': ActionSurveyList(),
    'admin_api_v2:survey-question-copy': ActionSurveyQuestionCopy(),
    'admin_api_v2:survey-question-detail': ActionSurveyQuestionDetail(),
    'admin_api_v2:survey-question-list': ActionSurveyQuestionList(),
    'admin_api_v2:survey-question-restore': ActionSurveyQuestionRestore(),
    'admin_api_v2:survey-question-show-condition-node-save-with-items-list':
        ActionSurveyQuestionShowConditionNodeSaveWithItemsList(),
    'admin_api_v2:survey-quiz': ActionSurveyQuiz(),
    'admin_api_v2:survey-submit-condition-node-save-with-items-list':
        ActionSurveySubmitConditionNodeSaveWithItemsList(),
    'admin_api_v2:survey-text-detail': ActionSurveyTextDetail(),
    'admin_api_v2:hook-subscription-notification-restart-list':
        ActionHookSubscriptionNotificationRestartList(),
    'admin_api_v2:hook-subscription-notification-cancel-list':
        ActionHookSubscriptionNotificationCancelList(),
    'admin_api_v2:hook-subscription-notification-restart':
        ActionHookSubscriptionNotificationRestartList(),
    'admin_api_v2:hook-subscription-notification-cancel':
        ActionHookSubscriptionNotificationCancelList(),
    'admin_api_v2:survey-access': ActionSurveyAccess(),
    'admin_api_v2:survey-restore': ActionSurveyRestore(),
}


def get_action_info(history_entry):
    action = ACTIONS.get(history_entry.endpoint)
    if action:
        return action.get_template(history_entry)
    return '%s %s' % (history_entry.method, history_entry.endpoint)
