#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Update log block statistics checker
# to see what the block rate is.
# by Luke Bryan
#

import time
import datetime
#sudo pip3 install simpledate
#Also matplotlib if you want plots.
from simpledate import SimpleDate
import statistics

def getStats( hrs ):
	#Given block times, count uploads within hypothetical block range time B.
	B = 60 * 60 * hrs
	blocks = {
		'Jul11' : SimpleDate(2016, 7, 11, 12+9, 17, tz='America/Los_Angeles').timestamp,
		'Jul9' : SimpleDate(2016, 7, 9,   12, 16, tz='America/Los_Angeles').timestamp,
		'Jul8' : SimpleDate(2016, 7, 8,  23, 27, tz='America/Los_Angeles').timestamp,
		'Jul7' : SimpleDate(2016, 7, 7, 22, 54, tz='America/Los_Angeles').timestamp,
		'Jul7Noon': SimpleDate(2016, 7, 7, 11, 32, tz='America/Los_Angeles').timestamp,
		'Jun3' : SimpleDate(2016, 6, 3, 12, 42, tz='America/Los_Angeles').timestamp,
		'May29' : SimpleDate(2016, 5, 29, 11, 3, tz='America/Los_Angeles').timestamp,
		'May28' : SimpleDate(2016, 5, 28, 12+5, 32, tz='America/Los_Angeles').timestamp,
		'May27' : SimpleDate(2016, 5, 27, 12+3, 56, tz='America/Los_Angeles').timestamp,
		'May26' : SimpleDate(2016, 5, 26, 1, 9, tz='America/Los_Angeles').timestamp,
		#Not enough data
		#'May5' : SimpleDate(2016, 5, 5, 12+3, 28, tz='America/Los_Angeles').timestamp,
		#'May4' : SimpleDate(2016, 5, 4, 4, 27, tz='America/Los_Angeles').timestamp,
		#'May3' : SimpleDate(2016, 5, 3, 12, 32, tz='America/Los_Angeles').timestamp,
		#'May2' : SimpleDate(2016, 5, 2, 12+7, 36, tz='America/Los_Angeles').timestamp,
	}
	
	#count how many uploads contributed to block on certain day:
	counts = {}	
	for time in blocks.keys():
		counts[ time ] = 0
	
	with open( 'UpdateTimings.log' ) as logfile:
		for line in logfile:
			cmd, start, end =  line.split()
			#Seconds, not ms:
			start = int(start) / 1000
			end = int(end) / 1000
			if 'Xcode' == cmd:
				for block in blocks.keys():
					blockTS = blocks[ block ]
					if blockTS - B <= start and start <= blockTS:
						counts[ block ] += 1 #within block range. count.
						#print( block, datetime.datetime.fromtimestamp( start ).strftime('%Y-%m-%d %H:%M:%S'), 
			             #  datetime.datetime.fromtimestamp( end ).strftime('%Y-%m-%d %H:%M:%S') )
	return counts

def main():
	x = []
	y = []
	for i in range(1, 80):
		print( "\n%s hour timespan:" % i )
		x.append( i )
		counts = getStats( i )
		numbers = [ counts[time] for time in counts]
		print( counts )
		print( numbers )
		print( statistics.mean( numbers ) )
		#print( statistics.stdev( numbers ) )
		#Don't want standard deviation, but likely deviation over mean - variance?
		var = statistics.variance( numbers)
		y.append(var)
		
	import matplotlib.pyplot as plt
	plt.plot(x, y, 'bo')
	plt.show()
	return 0

if __name__ == '__main__':
	main()

