import os
import re
import sys
import time
import decimal
import datetime
import numpy as np
import matplotlib.dates as md
import matplotlib.pyplot as plt
import matplotlib.dates as mdate
import matplotlib as mpl


# Remove meaningless zeros
def dropzeros(number):
    mynum = decimal.Decimal(number).normalize()
    # e.g 22000 --> Decimal('2.2E+4')
    return mynum.__trunc__() if not mynum % 1 else float(mynum)


# Regular expresion to recognize time and daemon names
regEx = re.compile("^(\d{10}) (\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) \
taurusi(\d+) ([a-z,0-9]+) ([a-z]+) \[(.*)\] (.*) <> (.*)$\n", re.IGNORECASE)


# Check if start or end point determined
# aka: Zooming
startTime = endTime = ""
if (len(sys.argv) == 3):
	startTime = dropzeros(time.mktime(datetime.datetime.strptime(sys.argv[1],\
                        "%Y/%m/%d-%H:%M:%S").timetuple()));
	endTime = dropzeros(time.mktime(datetime.datetime.strptime(sys.argv[2],\
                        "%Y/%m/%d-%H:%M:%S").timetuple()));


# Reading the log file and inserting information into syslog.plot
daemonList = []
file = open("syslog.plot", "w")
for line in sys.stdin:
	newTimeStamp = regEx.sub("\g<1>", line)
	if (len(sys.argv) == 3 and newTimeStamp < startTime): continue
	if (len(sys.argv) == 3 and newTimeStamp > endTime): continue
	if startTime == '': startTime = newTimeStamp

	oldTimeStamp = regEx.sub("\g<2> \g<3>", line)
	nodeName = regEx.sub("\g<4>", line)
	daemonName = regEx.sub("\g<5>", line)

	if daemonName not in daemonList:
		daemonList.append(daemonName)

#	print str(newTimeStamp)+'\t'+oldTimeStamp+'\t'+daemonName+'\t'+str(daemonList.index(daemonName))
	file.write(str(oldTimeStamp)+","+str(daemonList.index(daemonName))+"\n")
file.close()

#newTimeStamp always keeps the last timestamp
fileName =    str(nodeName) + "_" + time.strftime('%Y%m%d%H%M%S',  time.gmtime(dropzeros(startTime)))\
                + "_" + time.strftime('%Y%m%d%H%M%S',  time.gmtime(dropzeros(newTimeStamp)))

os.rename("syslog.plot", fileName+".plot");


# Check if there was at leas one entry in log file
if (len(daemonList) == 0):
	print "Nothing found"
	exit();


# Initializing the figure environment and drawing the figure
plt.figure(figsize=(12.21,5.10))
numOfXTicks = 20
date, daemon = np.loadtxt(fileName+".plot", unpack=True, delimiter=",", 
        converters={ 0: mdate.strpdate2num('%Y-%m-%d %H:%M:%S')})
minX=min(date);
maxX=max(date);
minY=min(daemon);
maxY=max(daemon);

ax=plt.gca()
xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S')
ax.xaxis.set_major_formatter(xfmt)

plt.title(nodeName);
plt.xlabel("Time (second)");
plt.ylabel("Reporter daemon");
plt.xticks(np.arange(minX, maxX, (maxX-minX)/numOfXTicks), rotation=45, ha='right')
ticks = ax.xaxis.get_majorticklocs();
ticks = np.append(ticks,[maxX]);
ax.xaxis.set_ticks(ticks);
plt.yticks(np.arange(minY, maxY+1, 1));

plt.xlim((minX,maxX));
plt.ylim((minY-1,maxY+1));
plt.grid(True)
#props = dict(boxstyle='round', facecolor='wheat', alpha=0.2)
#ax.text(0.05, 0.95, "Kernel", transform=ax.transAxes, fontsize=14, verticalalignment='top', bbox=props)
ax.set_yticklabels(daemonList)
plt.scatter(date, daemon, alpha=0.5);
plt.savefig(fileName+".png",bbox_inches="tight", dpi=100);

#	plt.plot([0, $finishingPoint], [maxNet, maxNet], color="r", linestyle="-.", linewidth=1);
#	plt.text(0, maxNet, plotLabel, fontsize=10, color="r");
#	plt.annotate("Completed\n $finishingPoint", xy=($finishingPoint, 0),\
#			xycoords="data", xytext=($finishingPoint - ($maxFinishingTime / 10), 120),\
#			textcoords="data", size=10, ha="center",\
#			bbox=dict(boxstyle="round4,pad=.5", fc="0.9"),\
#			arrowprops=dict(arrowstyle="->", connectionstyle="angle,angleA=0,angleB=-90,rad=10"));
