import datetime

register_account_ = "assets:current:cash:register"
revenue_accounts_ = ["revenue:sales:edibles", "revenue:sales:materials"]
inventory_accounts_ = ["assets:current:inventory-edibles", "assets:current:inventory-materials" ]
schwund_account_ = "expenses:shrinkage"
donation_account_ = "expenses:shrinkage"
#donation_account_ = "revenue:donations:shrinkage"
default_currency_ = "EUR"

hledger_ledgerpath_=os.path.split(__file__)[0]+'/../Ledgers/r3.ledger'

ledger_fileobj = open(hledger_ledgerpath_)
journal = ledger.sortTransactionsByDate(
    list(ledger.createTempAccountsForAndConvertFromMultiDatePostings(
        ledger.parseJournal(ledger_fileobj)
        ))
    )
ledger_fileobj.close()

dates = []
interval = [] # days between taking inventory
d1 = []
d2 = []
d3 = []
d4 = []

# 3 datapoints of umsatz:
# - minimum break even point: summmer der einkaufspreise der getränke/snaks die aus assets:current:inventory-edibles verkauft wurden
# - tatsächlicher umsatz: erwarteter umsatz mit getränken - schwund in euro
# - maximum we should get: erw. umsatz mit getränken
    ## Convert FutureAmoutFractions to real Amounts
    for p in new_transaction.postings:
        if isinstance(p.amount, FutureAmountFraction):
            p.amount.convertToAmount(Amount(amountCmp,currency))
        if date2 != date:
            p.setDate(date2)
    new_transaction.prependPosting(Posting(elba_primary_account_, Amount(amountCmp,currency))).addComment(description).setDate(date)

    transactions.append(new_transaction)


not_balanced = [t for t in transactions if not t.isBalanced()]
if len(not_balanced) > 0:
    print("ERROR: the following transactions are not balanced !!\n", file=sys.stderr)
    print("\n\n".join(map(str,(sortTransactionsByDate(not_balanced)))), file=sys.stderr)
    sys.exit(1)
assert(len(not_balanced) == 0)

transactions = sortTransactionsByDate(transactions)

if len(sys.argv) > 1:
    re_amt = re.compile(re_amount_str_3captures)
    final_assert_m = re_amt.match(sys.argv[1].strip())
    if not final_assert_m is None:
        assertamt = parseAmount(*final_assert_m.group(1,2,3))
        transactions[-1].postings[0].addPostPostingAssertAmount(assertamt)

print("\n\n".join(map(str,(transactions))))

transactions = list(
                filter(
                    lambda t: len(t.postings) > 0, ledger.parseJournal(
                        ledger.getHLedger(hledger_ledgerpath_, ["--cost"] + sys.argv[1:],depth=None)
                        )
                    )
                )
print("done")

print("depth limiting transactions ...", end="", flush=True)
for t in transactions:
    t.reduceDepth(depth)
print("done")

transactions_with_tempaccounts_without_multidates = list(ledger.sortTransactionsByDate(
        list(ledger.createTempAccountsForAndConvertFromMultiDatePostings(transactions))
    ))

## make running sum of journal for the graphs
print("calculating running sum ...", end="", flush=True)
running_sum_ = list(ledger.runningSumOfJournal(transactions_with_tempaccounts_without_multidates))
print("done")
print("calculating cashflow ...", end="")
acct_currency_accts_cashflow_dict_ = ledger.cashflowPerAccount(transactions, addinsubaccounts=True)
print("done")


graph = VisJsGraph()

def logScaleValue(x):
    e=1.3
            print("unknown category:", category, file=sys.stderr)
            assert (False)
        sourceacct = monefy_category_shorthands[category]

    if targetacct in monefy_ignore_accounts_:
        continue
        new_transaction.addPosting(Posting(sourceacct, nix,
                                           comment)).addTag("monefy")

    transactions.append(new_transaction)

not_balanced = [t for t in transactions if not t.isBalanced()]
if len(not_balanced) > 0:
    print("ERROR: the following transactions are not balanced !!\n",
          file=sys.stderr)
    print("\n\n".join(map(str, (sortTransactionsByDate(not_balanced)))),
          file=sys.stderr)
    sys.exit(1)
assert (len(not_balanced) == 0)


def mergeIdenticalTransactionsInList(lst, itm):
    t, orig_index = itm
    if len(lst
           ) > 0 and t.date == lst[-1][0].date and t.name == lst[-1][0].name:
        #merge transactions, give it largest sorting index, so merged transaction get sorted at position of its youngest subtransaction
        origt = lst[-1][0]
        origt.mergeInPostingsFrom(t)
        lst[-1] = (origt, orig_index)
    else:
        lst.append(itm)