from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404

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


def index(request):
    return render(request, 'costs/index.html')


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

    return render(
        request, 'costs/documents_list.html', {
            'documents': docs,
            'breadcrumbs': breadcrumbs,
        })


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,
            'breadcrumbs': breadcrumbs,
        })


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())
    monthly_fas = context['unit_goods_value_share']/36
    context.update({
        'breadcrumbs': breadcrumbs,
        'document': doc,
        'service': service,
        'costs_uses': costs_uses,
        'goods_uses': goods_uses,
        'services_uses': services_uses,
        'monthly_fas': monthly_fas,
        'consolidated_cost': monthly_fas + context['unit_recurring_price'],
    })
    return render(request, 'costs/service_detail.html', context)
