# coding=utf8
from __future__ import absolute_import

from django.db.models.query_utils import Q
from rest_framework.response import Response
from rest_framework.decorators import action
from core.framework.manageviews import TemplateHTMLRendererView, \
    ManageResponseViewSet, ManageListView, ManageAddView, \
    ManageEditView, ManageActiveView, ManageDeleteView
from core.framework.permissions import IsAuthManager
from core.framework.pagination import ManagePagination
from core.framework.response import MangeAPIResponse

from apps.task.models import Task
from apps.task.filters import ManageTaskFilter
from apps.manage.apps.task.serializers import ManageTaskSerializer, ManageTaskAddSerializer
from fish.constant import FAIL


class ManageTaskView(TemplateHTMLRendererView):
    template_name = 'manage/apps/task/index.html'
    permission_classes = [IsAuthManager]

    def get(self, request):
        manage = {
            'filter': ManageTaskFilter,
            'actions': [{'id': 'add', 'text': '新建提醒'}],
        }
        serializer = ManageTaskSerializer()
        return Response({'add_serializer': ManageTaskAddSerializer,
                         'edit_serializer': serializer,
                         'manage': manage})


class ManageTaskAPIViewSet(ManageListView, ManageAddView,
                           ManageEditView, ManageDeleteView,
                           ManageResponseViewSet):
    model = Task
    filter_cls = ManageTaskFilter
    queryset = Task.objects.all()
    permission_classes = [IsAuthManager]
    serializer_class = ManageTaskSerializer
    add_serializer_class = ManageTaskAddSerializer
    pagination_class = ManagePagination

    @action(methods=['post'], detail=False)
    def cancel(self, request, **kwargs):
        pk = request.GET.get('id')
        task = Task.objects.get(pk=pk)
        task.state = FAIL
        task.save(update_fields=['state'])
        task.set_active_list(task.instrument)
        return MangeAPIResponse()
