import datetime
from decimal import Decimal
import uuid
from brewman.models import DBSession
from brewman.models.master import LedgerBase
from brewman.models.operations import journals_valid
from brewman.models.voucher import Journal, Voucher, VoucherType

__author__ = 'tanshu'

def journal_create_voucher(json, user):
    dt = datetime.datetime.strptime(json['Date'], '%d-%b-%Y')
    voucher = Voucher(date=dt, narration=json['Narration'], user_id=user.id, type=VoucherType.by_name(json['Type']))
    DBSession.add(voucher)
    for item in json['Journals']:
        ledger = LedgerBase.by_id(uuid.UUID(item['Ledger']['LedgerID']))
        journal_id = uuid.UUID(item['JournalID']) if 'JournalID' in item else None
        amount = round(Decimal(item['Amount']), 2)
        journal = Journal(id=journal_id, amount=amount, debit=int(item['Debit']), ledger_id=ledger.id,
            cost_center_id=ledger.costcenter_id)
        voucher.journals.append(journal)
        DBSession.add(journal)
    journals_valid(voucher)
    return voucher


def journal_update_voucher(voucher, json, user):
    voucher.date = datetime.datetime.strptime(json['Date'], '%d-%b-%Y')
    voucher.narration = json['Narration']
    voucher.user_id = user.id
    voucher.posted = False
    voucher.last_edit_date = datetime.datetime.utcnow()

    newJournals = json['Journals']
    for i in range(len(voucher.journals), 0, -1):
        item = voucher.journals[i - 1]
        found = False
        for i in range(len(newJournals), 0, -1):
            j = newJournals[i - 1]
            if 'JournalID' in j and item.id == uuid.UUID(j['JournalID']):
                ledger = LedgerBase.by_id(uuid.UUID(j['Ledger']['LedgerID']))
                found = True
                item.debit = int(j['Debit'])
                item.amount = round(Decimal(j['Amount']), 2)
                item.ledger_id = ledger.id
                item.cost_center_id = ledger.costcenter_id
                newJournals.remove(j)
                break
        if not found:
            voucher.journals.remove(item)
    for j in newJournals:
        ledger = LedgerBase.by_id(uuid.UUID(j['Ledger']['LedgerID']))
        journal = Journal(id=None, amount=round(Decimal(j['Amount']), 2), debit=int(j['Debit']), ledger_id=ledger.id,
            cost_center_id=ledger.costcenter_id)
        DBSession.add(journal)
        voucher.journals.append(journal)
    journals_valid(voucher)
    return voucher


