import datetime
from sqlalchemy.sql.expression import func, desc

from pyramid.view import view_config

from brewman.models import DBSession
from brewman.models.master import CostCenter, Product

from brewman.models.voucher import Voucher, Journal, Inventory, VoucherType
from brewman.views.services.session import session_period_start, session_period_finish


@view_config(request_method='GET', route_name='purchases', renderer='brewman:templates/angular_base.mako',
             permission='Purchases')
def html(request):
    return {}


@view_config(request_method='GET', route_name='api_purchases', renderer='json', permission='Purchases')
def report_blank(request):
    return {'StartDate': session_period_start(request), 'FinishDate': session_period_finish(request), 'Body': []}


@view_config(request_method='GET', route_name='api_purchases', request_param='s', renderer='json',
             permission='Purchases')
def report_data(request):
    start_date = request.GET.get('s', None)
    finish_date = request.GET.get('f', None)
    return build_report(request, start_date, finish_date)


def build_report(request, start_date, finish_date):
    report = {'StartDate': start_date, 'FinishDate': finish_date, 'Body': []}

    quantity_sum = func.sum(Journal.debit * Inventory.quantity).label('Quantity')
    amount_sum = func.sum(Journal.debit * Inventory.quantity * Inventory.rate * (1 + Inventory.tax)).label('Amount')
    query = DBSession.query(Product, quantity_sum, amount_sum) \
        .join(Product.inventories).join(Inventory.voucher).join(Voucher.journals) \
        .filter(Voucher.date >= datetime.datetime.strptime(start_date, '%d-%b-%Y')) \
        .filter(Voucher.date <= datetime.datetime.strptime(finish_date, '%d-%b-%Y')) \
        .filter(Voucher.type != VoucherType.by_name('Issue').id) \
        .filter(Journal.cost_center_id == CostCenter.cost_center_purchase()) \
        .group_by(Product).order_by(desc(amount_sum)).all()

    total_amount = 0
    for product, quantity, amount in query:
        rate = amount / quantity if quantity != 0 else 0
        total_amount += amount
        row = {'Name': product.full_name, 'Quantity': quantity, 'Rate': rate, 'Amount': amount,
               'Url': request.route_url('product_ledger_id', id=product.id,
                                        _query={'StartDate': start_date, 'FinishDate': finish_date})}
        report['Body'].append(row)
    report['Footer'] = [{'Name': "Total", 'Amount': total_amount}]
    return report


