#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# This program is Copyright (C) 2017, Paul Lutus
# and is released under the GPL:
# https://www.gnu.org/licenses/gpl-3.0.en.html

from collections import defaultdict
from piecash import open_book

# change this path to suit your needs
data_path = '/netbackup/data/python_projects/DATABASE_gnucash_related_programs/all_accounts.sqlite3.gnucash'

with open_book(data_path) as book:
  
    account = book.root_account.children(name='Assets').children(name='Current Credit Card')
    categories = defaultdict(int)
    count = defaultdict(int)
    
    print('Analysis - account: "%s"' % account.name)
    
    print("Transactions by date:")
    print("    %-25s : %-32s : %10s : %10s" % ("Date/Time","Description","Amount","Subtotal"))
    print("    %s" % ("-" * 95))
    balance = 0
    # sort transactions by date
    for transaction in sorted(
        book.transactions,
        key=lambda t:t.post_date
      ):
      for split in transaction.splits:
        if account == split.account:
          balance += split.value
          # accumulate this transaction by category
          categories[transaction.description] += split.value
          count[transaction.description] += 1
          # display this transaction
          print("    %-25s : %-32s : %10.2f : %10.2f" %
            (
              transaction.post_date,
              transaction.description,
              split.value,
              balance
            )
          )
    print("Balance: %.2f" % balance)
    
    print("Transactions by category:")
    print("    %-32s : %6s : %10s : %10s" % ("Description","Count","Amount","Balance"))
    print("    %s" % ("-" * 80))
    balance = 0
    # sort by total category amount
    for name in sorted(
        categories,
        key=lambda n:categories[n]
      ):
      balance += categories[name]
      print("    %-32s : %6d : %10.2f : %10.2f" %
        (
          name,
          count[name],
          categories[name],
          balance
        )
      )
    print("Balance: %.2f" % balance)
