# coding: utf-8
#
# written by TRex, modified by Meillo, with help by JTH
 
import urllib
#from six.moves import urllib
from datetime import datetime, date
from itertools import groupby
from sys import argv
 
import matplotlib
 
# must be executed before pyplot import
matplotlib.use('agg')
import matplotlib.pyplot as plt
 
if len(argv) != 2:
    print("Usage: " + argv[0] + " OUTFILE.png")
    exit(1)
outfile = argv[1]
 

#with urllib2.urlopen('http://tmp.marmaro.de/dfde/dfde-besucher.log') as response:
    #html = response.read().strip()

#html = urllib.urlopen('http://tmp.marmaro.de/dfde/dfde-besucher.log').read()
#lines = html.decode("utf-8").splitlines()
#data = list(map(unicode.split, lines))

html = urllib.urlopen('http://tmp.marmaro.de/dfde/dfde-besucher.log').read()
data = map(str.split, html.splitlines())

#with open("dfde-besucher.log") as f:
#    data = map(str.split, f.readlines())
 
 
def get_visitor_count(row):
    return int(row[4]) if len(row) > 4 else 0
 
 
def get_datetime(row):
    year, month, day = [int(x) for x in row[0].split('-')]
    hour, minute = map(int, row[1].split(":"))
    return datetime(year, month, day, hour, minute)
 
 
def _groupy(item):
    return item[0].year, item[0].month, item[0].day
 
 
def get_date_grouped_list(list_):
    agg_list = []
    for ((year, month, day), items) in groupby(list_, _groupy):
	agg_list.append((date(year, month, day), sum([x[1] for x in items])))
    return agg_list
 
 
aggdata = get_date_grouped_list([(get_datetime(x), get_visitor_count(x)) for x in data])
 
fig = plt.figure(figsize=(15, 7))
 
plt.plot([x[0] for x in aggdata], [x[1] for x in aggdata], label="Besucher")
plt.xlabel("Datum")
plt.ylabel("Besucherzahl")
#plt.xticks(rotation=70)
plt.legend()
 
plt.savefig(outfile)
plt.close(fig)
 
exit()

