import datetime
from pyramid.view import view_config
from brewman.models.voucher import Batch


@view_config(request_method='GET', route_name='api_batch', renderer='json', permission='Authenticated')
def batch_term(request):
    filter = request.GET.get('term', None)
    filter = filter if filter is not None and filter.strip() is not '' else None
    count = request.GET.get('count', None)
    count = None if count is None or count == '' else int(count)
    date = request.GET.get('date', None)
    date = None if count is None or count == '' else datetime.datetime.strptime(date, '%d-%b-%Y')
    list = []
    for index, item in enumerate(Batch.list(filter, include_nil=False, date=date)):
        text = "{0} ({1}) {2:.2f}@{3:.2f} from {4}".format(item.product.name, item.product.units,
            item.quantity_remaining, item.rate, item.name.strftime('%d-%b-%Y'))
        list.append({'BatchID': item.id, 'Name': text, 'QuantityRemaining': item.quantity_remaining,
                     'Rate': item.rate, 'Tax': item.tax, 'Discount': item.discount,
                     'Product': {'ProductID': item.product.id, 'Name': item.product.name, 'Units': item.product.units}})
        if count is not None and index == count - 1:
            break
    return list
