from sqlalchemy.orm import joinedload_all

from pyramid.view import view_config

from brewman.models.voucher import Voucher, Journal, VoucherType
from brewman.views.services.voucher import get_edit_url

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


@view_config(request_method='GET', route_name='api_unposted', renderer='json', permission='Post Vouchers')
def report_data(request):
    return build_report(request)

def build_report(request):
    body = []

    query = Voucher.query().options(joinedload_all(Voucher.journals, Journal.ledger, innerjoin=True))\
    .filter(Voucher.posted == False)\
    .filter(Voucher.type != VoucherType.by_name('Issue').id)\
    .order_by(Voucher.date).order_by(Voucher.last_edit_date).all()

    for voucher in query:
        debit = 0
        credit = 0
        nameDebit = ""
        nameCredit = ""
        for journal in voucher.journals:
            if journal.debit == 1:
                debit += journal.amount
                nameDebit += "{0} / ".format(journal.ledger.name)
            else:
                credit += journal.amount
                nameCredit += "{0} / ".format(journal.ledger.name)
        nameDebit = nameDebit[:-3]
        nameCredit = nameCredit[:-3]

        body.append({'Date': voucher.date.strftime('%d-%b-%Y'), 'Url': get_edit_url(request, voucher),
                               'Type': VoucherType.by_id(voucher.type).name,
                               'Narration': voucher.narration, 'Posted': voucher.posted,
                               'DebitN': nameDebit, 'DebitA': debit, 'CreditN': nameCredit,'CreditA': credit})

    return body