from random import choice

from django.contrib import messages
from django.http import Http404, HttpResponseRedirect
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views.generic.edit import UpdateView

from core.custom_annotations import group_required, in_groups
from core.forms import FeedbackForm
from core.grady_speak import grady_says
from core.models import Feedback, Submission, SubmissionType


@group_required('Tutors')
def create_feedback(request, type_slug=None):
    # assign does nothing if tutor has unfinished feedback
    assigned = Submission.assign_tutor(request.user, type_slug)
    feedback = Feedback.tutor_unfinished_feedback(request.user)
    if not feedback:
        if type_slug:
            messages.info(request, "No more submissions of type '%s' available." %
                          SubmissionType.objects.get(slug=type_slug))
        else:
            messages.success(request, "Well done! There is no more work to do.")
        return HttpResponseRedirect(reverse('start'))
    elif not assigned:
        messages.info(request, "You have got unfinished business. Please finish this task first.")
    return HttpResponseRedirect(reverse('FeedbackEdit', args=(feedback.slug,)))


@group_required('Reviewers')
def delete_feedback(request, feedback_slug):
    """ Hook to ensure object is owned by request.user. """
    instance = Feedback.objects.get(slug=feedback_slug)
    instance.delete()
    return HttpResponseRedirect(reverse('start'))


class FeedbackEdit(UpdateView):

    """docstring for FeedbackCreate"""

    form_class = FeedbackForm
    template_name = 'core/feedback_form.html'
    success_url = '/start/'

    @method_decorator(group_required('Tutors', 'Reviewers'))
    def dispatch(self, *args, **kwargs):
        return super(FeedbackEdit, self).dispatch(*args, **kwargs)

    def get_object(self):
        instance = Feedback.objects.get(slug=self.kwargs['feedback_slug'])
        if instance.of_tutor == self.request.user or in_groups(self.request.user, ('Reviewers', )):
            return instance
        elif instance.status == Feedback.OPEN:
            instance.reassign_to_tutor(self.request.user)
            return instance
        raise Http404

    def form_valid(self, form):
        """
        If the form is valid, redirect to the supplied URL.
        """
        if form.is_valid():
            form.instance.text = self.request.POST['text']
            if form.instance.status == Feedback.ACCEPTED:
                form.instance.finalize_feedback(self.request.user)
            else:
                form.instance.unfinalize_feedback()

        # ugly needs patch
        if 'Next' in self.request.POST['update']:
            if in_groups(self.request.user, ('Reviewers',)):

                needs_review = Feedback.objects.filter(
                    status=Feedback.NEEDS_REVIEW,
                    of_submission__type=form.instance.of_submission.type
                )

                if needs_review:
                    return HttpResponseRedirect(reverse('FeedbackEdit', args=(needs_review[0].slug,)))

            else: # in_groups(self.request.user, ('Tutor',)):
                return HttpResponseRedirect(reverse('CreateFeedbackForType', args=(form.instance.of_submission.type.slug,)))

        return HttpResponseRedirect(self.get_success_url())

    def get_context_data(self, **kwargs):
        context = super(FeedbackEdit, self).get_context_data(**kwargs)
        context['grady_says'] = choice(grady_says)
        return context