import datetime
import uuid

import pkg_resources
from pyramid.response import FileResponse
from sqlalchemy.orm import joinedload_all
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.validation_exception import TryCatchFunction
from brewman.models.voucher import Voucher, Journal, VoucherType
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='ledger_id', permission='Ledger')
@view_config(request_method='GET', route_name='ledger', permission='Ledger')
def html(request):
    package, resource = 'brewman:static/base.html'.split(':', 1)
    file = pkg_resources.resource_filename(package, resource)
    return FileResponse(file, request=request)


@view_config(request_method='GET', route_name='api_ledger', renderer='json', permission='Ledger')
def show_blank(request):
    return {'StartDate': session_period_start(request),
            'FinishDate': session_period_finish(request), 'Ledger': None, 'Body': []}


@view_config(request_method='GET', route_name='api_ledger_id', renderer='json', permission='Ledger')
@TryCatchFunction
def show_data(request):
    ledger_id = request.matchdict['id']
    ledger = LedgerBase.by_id(uuid.UUID(ledger_id))
    start_date = request.GET.get('StartDate', session_period_start(request))
    finish_date = request.GET.get('FinishDate', session_period_finish(request))
    info = {'StartDate': start_date, 'FinishDate': finish_date,
            'Ledger': {'LedgerID': ledger.id, 'Name': ledger.name},
            'Body': []}
    build_report(request, info)
    return info


def build_report(request, info):
    ledger_id = info['Ledger']['LedgerID']
    start_date = info['StartDate']
    finish_date = info['FinishDate']
    opening = opening_balance(ledger_id, start_date)
    info['Body'].append(opening)

    query = Voucher.query().options(joinedload_all(Voucher.journals, Journal.ledger, innerjoin=True)) \
        .filter(Voucher.journals.any(Journal.ledger_id == ledger_id)) \
        .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
        journal_debit = 0
        name = ""
        for journal in voucher.journals:
            if journal.ledger_id == ledger_id:
                journal_debit = journal.debit
                if journal.debit == 1:
                    debit = journal.amount
                    credit = 0
                else:
                    credit = journal.amount
                    debit = 0
        for journal in voucher.journals:
            if journal.debit != journal_debit:
                name += "{0} / ".format(journal.ledger.name)
        name = name[:-3]
        info['Body'].append(
            {'ID': voucher.id, 'Date': voucher.date.strftime('%d-%b-%Y'), 'Name': name,
             'Url': get_edit_url(request, voucher), 'Type': VoucherType.by_id(voucher.type).name,
             'Narration': voucher.narration, 'Debit': debit, 'Credit': credit, 'Posted': voucher.posted})


def opening_balance(ledger_id, start_date):
    opening = DBSession.query(func.sum(Journal.amount * Journal.debit)) \
        .join(Journal.voucher) \
        .filter(Voucher.date < datetime.datetime.strptime(start_date, '%d-%b-%Y')) \
        .filter(Voucher.type != VoucherType.by_name('Issue').id) \
        .filter(Journal.ledger_id == ledger_id) \
        .scalar()
    opening = 0 if opening is None else opening
    if opening < 0:
        credit = opening * -1
        debit = 0
    else:
        debit = opening
        credit = 0
    return {'Date': start_date, 'ID': 'OB', 'Name': 'Opening Balance', 'Type': 'Opening Balance',
            'Narration': '', 'Debit': debit, 'Credit': credit, 'Posted': True}
