# -*- coding: utf-8 -*-
from django.contrib.contenttypes.models import ContentType
from django.http import Http404
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response

from events.history.models import HistoryRawEntry
from events.rest_framework_contrib.mixins import ExternalGenericApiViewV1Mixin
from events.rest_framework_contrib.permissions import IsSuperUser, IsSupport, ANY
from events.surveyme.models import Survey
from events.support import serializers, utils


class SupportViewSet(ExternalGenericApiViewV1Mixin, viewsets.GenericViewSet):
    permission_classes = [ANY(IsSuperUser, IsSupport)]
    detail = None

    def _save_history(self, request, survey_id):
        ct = ContentType.objects.get_for_model(Survey)
        HistoryRawEntry.objects.create_raw_entry(request, ct, survey_id)

    @action(methods=['post'], url_path='change-owner', detail=False)
    def change_owner(self, request, *args, **kwargs):
        serializer = serializers.ChangeOwnerSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        result = utils.change_owner(**serializer.validated_data)
        self._save_history(request, serializer.validated_data['survey_id'])
        return Response(result)

    @action(methods=['post'], url_path='change-organization', detail=False)
    def change_organization(self, request, *args, **kwargs):
        serializer = serializers.ChangeOrganizationSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        result = utils.change_organization(**serializer.validated_data)
        self._save_history(request, serializer.validated_data['survey_id'])
        return Response(result)

    @action(methods=['get'], url_path='tasks/(?P<task_id>[a-fA-F0-9\\-]+)', detail=False)
    def tasks(self, request, task_id=None):
        result = utils.get_task_info(task_id)
        return Response(result)

    @action(methods=['get'], url_path='surveys/(?P<survey_id>[a-fA-F0-9]+)', detail=False)
    def surveys(self, request, survey_id=None):
        try:
            result = utils.get_survey_info(survey_id)
        except Survey.DoesNotExist:
            raise Http404
        else:
            return Response(result)
