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, LedgerType, LedgerBase

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

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


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


@view_config(request_method='GET', route_name='api_purchase_entries', request_param='StartDate', renderer='json',
    permission='Purchase Entries')
def report_data(request):
    start_date = request.GET.get('StartDate', None)
    finish_date = request.GET.get('FinishDate', 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': []}
    start_date = datetime.datetime.strptime(start_date, '%d-%b-%Y')
    finish_date = datetime.datetime.strptime(finish_date, '%d-%b-%Y')

    query = DBSession.query(Voucher)\
    .filter(Voucher.date >= start_date)\
    .filter(Voucher.date <= finish_date)\
    .filter(Voucher.type == VoucherType.by_name('Purchase').id)\
    .order_by(Voucher.date).all()

    for voucher in query:
        journal = [j for j in voucher.journals if j.debit == -1]
        journal = journal[0]
        row = {'Date': voucher.date.strftime('%d-%b-%Y'), 'Supplier': journal.ledger.name,
                'Url': get_edit_url(request, voucher), 'Products': []}
        for item in voucher.inventories:
            row['Products'].append(
                {'Product': item.product.full_name, 'Quantity': item.quantity, 'Rate': item.rate, 'Tax': item.tax,
                 'Amount': item.amount})
        report['Body'].append(row)
    return report


