#!/usr/bin/env python3
import argparse
from decimal import *

from pymongo import MongoClient

parser = argparse.ArgumentParser(description="view")
parser.add_argument('mongo_url', type=str)
parser.add_argument('db', type=str)
parser.add_argument('collection', type=str)

args = parser.parse_args()

client = MongoClient(args.mongo_url)
db = client[args.db]
collection = db[args.collection]

currencies = ['RMB', 'USD', 'JPY', 'EUR']

date_set = set()

documents = []
cursor = collection.find({})
for document in cursor:
    date_set.add(document['time'])
    documents.append(document)

date_set = sorted(date_set)

results = {}

for date in date_set:
    for document in documents:
        if document['time'] == date:
            key = document['name'] + date
            if key in results:
                results[key]['income'] += Decimal(document['income'])
                results[key]['expend'] += document['expend']
            else:
                results[key] = {
                    'name': document['name'],
                    'income': Decimal(document['income']),
                    'expend': document['expend'],
                    'time': date
                }

def sort_value(elem):
    weight = { 'RMB': '1', 'USD': '2', 'JPY': '3', 'EUR': '4' }
    return elem['time'] + weight[elem['name']]

values = list(results.values())
values.sort(key=sort_value)

print("%-6s %-12s %-10s %-16s" % ("name", "income", "expend", "time"))
for value in values:
    print("%-6s %-12.2f %-10.2f %-16s" % (value['name'], value['income'], value['expend'], value['time']))
