#!/usr/bin/env python

import datetime

from database import Database

def main():
    db = Database()
    now = datetime.datetime.now()
    todayfilter = "'%4d/%02d/%02d%%'"%(now.year,now.month,now.day)
    apps = db.get_intervals(
        'idle = 0 and start like '+todayfilter, distinct='app')

    app_usage = []

    for app in apps:
        freq = db.count_intervals(
            "idle = 0 and app = '"+app+"' and start like "+todayfilter)
        app_usage.append((freq, app))

    app_usage = sorted(app_usage, key=lambda x : x[0])
    app_usage.reverse()

    # add all frequencies
    total_int = reduce(lambda x,y: x+y, map(lambda x: x[0], app_usage))

    print 'Today\'s Top app usage (for %s hours)'%(now.strftime('%H'),)
    print '-'*30
    for appu in app_usage:
        print '%20s    %2d %%'%(appu[1], appu[0]*100/total_int)

    nactive = db.count_intervals('idle = 0 and start like '+todayfilter)
    nidle = db.count_intervals('idle = 1 and start like '+todayfilter)

    print ' '
    print 'Active factor: '
    print '-'*30
    print '%.2f %%'%(nactive*100./(nactive+nidle))

if __name__ == '__main__':
    main()
