# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import logging

from django.conf import settings
from django.contrib.auth.decorators import permission_required
from django.core.urlresolvers import reverse_lazy
from django.db import transaction
from django.http import HttpResponse, HttpResponseBadRequest
from django.http import HttpResponseForbidden
from django.utils.decorators import method_decorator
from django.views.generic import View
from django.views.generic import ListView
from django.views.generic import DeleteView
from django_yauth.decorators import yalogin_required

from core.models import Protocol
from core.models import Reward
from app.tasks import check_document_ticket

logger = logging.getLogger(__name__)


class ProtocolListView(ListView):
    model = Protocol
    paginate_by = 10
    template_name = 'protocol.html'

    @method_decorator(yalogin_required)
    @method_decorator(permission_required('core.add_protocol',
                                          raise_exception=True))
    def dispatch(self, request, *args, **kwargs):
        return super(ProtocolListView, self).dispatch(
            request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(ProtocolListView, self).get_context_data(**kwargs)
        context['base_ticket_url'] = settings.STARTREK_FRONTEND_HOST
        return context


class BaseProtocolView(View):
    cfo_dict = dict(Reward.DEPARTMENTS)

    @method_decorator(yalogin_required)
    @method_decorator(permission_required('core.add_protocol',
                                          raise_exception=True))
    def dispatch(self, request, *args, **kwargs):
        return super(BaseProtocolView, self).dispatch(
            request, *args, **kwargs)

    def _create_report(self, pk, response):
        protocol = Protocol.objects.get(pk=pk)
        file = getattr(protocol, self.field_name)
        response.write(file)
        return response


class ProtocolFileView(BaseProtocolView):
    field_name = 'protocol_file'

    def get(self, request, pk):
        response = HttpResponse(content_type = 'application/pdf')
        return self._create_report(pk, response)


class FinancialReportFileView(BaseProtocolView):
    field_name = 'financial_report_file'

    def get(self, request, pk):
        response = HttpResponse(content_type = 'application/vnd.ms-excel')
        return self._create_report(pk, response)


class FinancialReportAuditView(View):
    def get(self, request):
        logger.info('Financial report audit started')
        ticket_key = request.GET.get('ticket_key')
        logger.info('Financial report audit requested for ticket {}'.format(ticket_key))
        try:
            protocol = Protocol.objects.get(ticket_document=ticket_key)
        except Protocol.DoesNotExist:
            logger.error('No prtotocol corresponds to {}'.format(ticket_key))
            return HttpResponseBadRequest('No corresponding protocol')
        except Protocol.MultipleObjectsReturned:
            logger.error('Multiple protocols correspond to {}'.format(ticket_key))
            return HttpResponseBadRequest('Multiple corresponding protocols')
        check_document_ticket.apply_async(args=(protocol.pk,))
        return HttpResponse(protocol.pk)
