from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponseBadRequest
from django.shortcuts import render, get_object_or_404

from .models import Document, Service, ServiceUse, CostUse, GoodUse


CONTENT_TYPES = {
    'html': 'text/html; charset=utf-8',
    'txt': 'text/plain; charset=utf-8',
}

def format_to_content_type(_format):
    if _format not in ('txt', 'html'):
        raise ValueError('Unknown format {}'.format(_format))
    else:
        return '{}; charset=utf-8'.format(CONTENT_TYPES[_format])

@login_required
def list_documents(request):
    breadcrumbs = (
        ('Documents', reverse('list-documents')),
    )
    docs = Document.objects.all()\
                           .prefetch_related('service_set')\
                           .order_by('-date')

    return render(
        request, 'costs/documents_list.html', {
            'documents': docs,
            'planning_documents': docs.filter(type=Document.TYPE_PLAN),
            'factual_documents': docs.filter(type=Document.TYPE_FACT),
            'breadcrumbs': breadcrumbs,
        })


@login_required
def detail_document(request, pk):
    doc = get_object_or_404(Document, pk=pk)

    breadcrumbs = (
        ('Documents', reverse('list-documents')),
        (str(doc), doc.get_absolute_url())
    )
    return render(
        request, 'costs/document_detail.html', {
            'document': doc,
            'other_documents': Document.objects.exclude(pk=doc.pk),
            'breadcrumbs': breadcrumbs,
            'total_recuring_costs': doc.get_total_recuring_costs(),
            'total_goods': doc.get_total_goods()
        })

@login_required
def compare_document(request, pk, other_pk):
    _format = request.GET.get('format', 'html')

    if _format not in ('html', 'txt'):
        return HttpResponseBadRequest('Wrong format : {}'.format(_format))

    doc = Document.objects.get(pk=pk)
    other_doc = Document.objects.get(pk=other_pk)

    breadcrumbs = (
        ('Documents', reverse('list-documents')),
        (str(doc), doc.get_absolute_url()),
        ('Variations depuis {}'.format(other_doc), request.path),
    )
    context = {
        'breadcrumbs': breadcrumbs,
        'document': doc,
        'other_document': other_doc,
        'other_documents': Document.objects.exclude(pk=doc.pk),
        'deltas': doc.compare(other_doc),
    }
    response = render(
        request,
        'costs/document_compare.{}'.format(_format),
        context,
        content_type=format_to_content_type(_format),
    )
    return response


@login_required
def detail_service(request, pk):
    service = Service.objects.get(pk=pk)

    doc = service.document
    breadcrumbs = (
        ('Documents', reverse('list-documents')),
        (str(doc), doc.get_absolute_url()),
        (service.name, service.get_absolute_url())
    )
    costs_uses = CostUse.objects.filter(service=service)
    goods_uses = GoodUse.objects.filter(service=service)
    services_uses = ServiceUse.objects.filter(service=service)

    context = {}
    context.update(service.get_prices())
    context.update({
        'breadcrumbs': breadcrumbs,
        'document': doc,
        'service': service,
        'costs_uses': costs_uses,
        'goods_uses': goods_uses,
        'services_uses': services_uses,
    })
    return render(request, 'costs/service_detail.html', context)
