import datetime
from sqlalchemy.sql.expression import func

from pyramid.view import view_config

from brewman.models import DBSession
from brewman.models.master import LedgerBase

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

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

@view_config(request_method='GET', route_name='api_trial_balance', renderer='json', permission='Trial Balance')
def report_blank(request):
    return {'Date': session_period_finish(request), 'Body': []}


@view_config(request_method='GET', route_name='api_trial_balance_date', renderer='json', permission='Trial Balance')
def report_data(request):
    date = request.matchdict.get('date', None)
    return {'Date': date, 'Body': build_report(date)}


def build_report(date):
    date = datetime.datetime.strptime(date, '%d-%b-%Y')
    amount_sum = func.sum(Journal.amount * Journal.debit).label('Amount')
    query = DBSession.query(LedgerBase, amount_sum)\
        .join(Journal.voucher).join(Journal.ledger)\
        .filter(Voucher.date <= date).filter(Voucher.type != VoucherType.by_name('Issue').id).group_by(LedgerBase)\
        .order_by(LedgerBase.type).order_by(func.abs(amount_sum).desc()).all()


    body = []
    for ledger, amount in query:
        if amount != 0:
            tag = 'Debit' if amount > 0 else 'Credit'
            body.append({'Type': ledger.type_object.name, 'Name': ledger.name, tag:amount})
    return body
