# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2016 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import json

from django.core.urlresolvers import reverse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.http import HttpResponse, Http404

from passerelle import utils

from .models import StubInvoicesConnector


class InvoicesView(DetailView):
    model = StubInvoicesConnector

    @utils.to_json('api')
    def get(self, request, *args, **kwargs):
        return [x for x in self.get_object().get_invoices() if not x.get('payment_date')]


class HistoryInvoicesView(DetailView):
    model = StubInvoicesConnector

    @utils.to_json('api')
    def get(self, request, *args, **kwargs):
        return [x for x in self.get_object().get_invoices() if x.get('payment_date')]


class InvoiceView(DetailView):
    model = StubInvoicesConnector

    @utils.to_json('api')
    def get(self, request, *args, **kwargs):
        return self.get_object().get_invoice(kwargs.get('invoice_id'))


class InvoicePDFView(DetailView):
    model = StubInvoicesConnector

    def get(self, request, *args, **kwargs):
        invoice_id = kwargs['invoice_id']
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="%s.pdf"' % invoice_id
        response.write('')
        return response


class InvoicePayView(DetailView):
    model = StubInvoicesConnector

    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(InvoicePayView, self).dispatch(*args, **kwargs)

    @utils.to_json('api')
    @utils.protected_api('can_access')
    def post(self, request, *args, **kwargs):
        return utils.response_for_json(request, {'data': None})
