from __future__ import unicode_literals

from decimal import Decimal
from datetime import datetime, timedelta

from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.core.urlresolvers import reverse, reverse_lazy
from django.shortcuts import get_object_or_404, render, redirect
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView

from .forms import GiveQuoteForm, ResolutionForm, SettleForm, CloseOutForm
from .models import Invoice, InvoiceAlteration, CustomerConflict
from source_utils.permission_mixins import FinanceCheckMixin, SuperUserCheckMixin
from source_utils.view_mixins import DeleteViewMixin
from source_utils.starters import Conflict


from reportlab.pdfgen import canvas
from django.http import HttpResponse

from .printing import MyPrint
from io import BytesIO


def print_users(request, slug):
    invoice = get_object_or_404(Invoice, slug=slug)
    if invoice.work_order.work_completed and not invoice.due_by:
        invoice.due_by = datetime.now()+timedelta(days=35)
        invoice.save()

    title = 'attachment; first_name="{}.pdf"'.format(slug)
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename={}'.format(
    	slug + "-invoice.pdf")
 
    buffer = BytesIO()
 
    report = MyPrint(buffer, 'Letter', slug)
    pdf = report.print_users()
 
    response.write(pdf)
    return response


class InvoiceMixin(FinanceCheckMixin):
    model = Invoice


class InvoicesOptionsListView(InvoiceMixin, ListView):
    success_url = reverse_lazy('customer_finance:invoice_lists')
    template_name = "customer_finance/optional_lists.html"
    paginate_by = 4

    def get_queryset(self):
        if self.args[0] == "owed":
            return Invoice.objects.filter(paid_in_full=False)
        elif self.args[0] == "conflicted":
            self.template_name = "customer_finance/conflicts.html"
            return CustomerConflict.objects.filter(conflict_resolution=None)
        elif self.args[0] == "active":
            return Invoice.objects.filter(closed_out=False)
        else:
            return Invoice.objects.all()

    def get_context_data(self, **kwargs):
        context = super(InvoicesOptionsListView, self).get_context_data(**kwargs)
        if self.args[0] == "owed":
            context['title'] = "Customer Invoices with Balances"
        elif self.args[0] == "conflicted":
            context['title'] = "Customer Invoices with Conflicts"
        elif self.args[0] == "active":
            context['title'] = "Active Customer Invoices"
        else:
            context['title'] = "All Customer Invoices"
        return context


class InvoiceDetailView(InvoiceMixin, DetailView):
    template_name = "customer_finance/invoice_detail.html"
    url_insert = "customer_finance:invoice_delete"

    def get_context_data(self, **kwargs):
        context = super(InvoiceDetailView, self).get_context_data(**kwargs)
        context['total_after_tax'] = self.object.invoice_quote.total_price_quoted
        context['total_tax'] = self.object.invoice_quote.tax_on_quote
        context['before_tax'] = self.object.invoice_quote.total_price_quoted - self.object.invoice_quote.tax_on_quote
        context['balance_due'] = self.object.get_balance_due()
        context['payment_schedule'] = self.object.get_payment_schedule()

        return context


class InvoiceEditMixin(InvoiceMixin, SuccessMessageMixin):