import datetime
from sqlalchemy.orm import joinedload_all

from pyramid.view import view_config

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


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


@view_config(request_method='GET', route_name='api_daybook', renderer='json', permission='Daybook')
def daybook_report(request):
    start_date = request.GET.get('StartDate', None)
    finish_date = request.GET.get('FinishDate', None)
    if start_date and finish_date:
        return build_report(request, start_date, finish_date)
    else:
        return {'StartDate': session_period_start(request),
                'FinishDate': session_period_finish(request), 'Body': []}


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

    query = Voucher.query().options(joinedload_all(Voucher.journals, Journal.ledger, innerjoin=True)) \
        .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) \
        .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]

        report['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 report
