from itertools import chain

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

from .models import Document, Service, 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)

    total_costs_price = sum(chain(
        (i.monthly_provision_share() for i in goods_uses),
        (i.cost_share() for i in costs_uses),
    ))

    total_goods_value_share = sum(i.value_share() for i in goods_uses)

    if service.subscriptions_count == 0:
        unit_costs_price = 0
        unit_goods_value_share = 0
    else:
        unit_costs_price = total_costs_price/service.subscriptions_count
        unit_goods_value_share = total_goods_value_share/service.subscriptions_count

    context = {
        'breadcrumbs': breadcrumbs,
        'document': doc,
        'service': service,
        'costs_uses': costs_uses,
        'goods_uses': goods_uses,
        'total_costs_price': total_costs_price,
        'unit_costs_price': unit_costs_price,

        'total_goods_value_share': total_goods_value_share,
        'unit_goods_value_share': unit_goods_value_share,
        'monthly_fas': unit_goods_value_share/12,
    }
    return render(request, 'costs/service_detail.html', context)
