import os, string, re
from stats import *

# all needed for excel file generation
import win32com, sys, string, win32api, traceback
import win32com.client.dynamic
from win32com.test.util import CheckClean
import pythoncom
from win32com.client import gencache
from pywintypes import Unicode


name = re.compile("(.*)txt$",re.I)
sult = re.compile("result_K(\d+)_M(\d+).txt", re.I)
path = "./res/"

"""
	Import all results from optimization
	It generates a global results file, with nice information
	In fact, it build a excel file
"""

container      = {}

def parse(filename, s):
	global container

	nb_elmt= int(s[0])
	method = int(s[1])
	temp = container[method]

	try:
		io = open(filename, 'r')
	except IOError:
		print "Error for %s file !" % filename
	else:
		tList = []
		for l in io.readlines():
			tList.append(float(l))
		temp[nb_elmt] = tList
		container[method] = temp


def showExcel(method):
	global container
	excel = win32com.client.Dispatch('Excel.Application')
	excel.Visible = 1
	excel.Workbooks.Add()
	
	
	letter = {1:'A',2:'B',3:'C',4:'D',5:'E',6:'F',7:'G',8:'H',9:'I',10:'J',11:'K',12:'L'}
	
	# informations
	nb_col = len(container[method])

	iMax = 0

	excel.ActiveSheet.Cells(1).Value = ("Method %i" % method)
	for i in container[method].keys():
	    excel.ActiveSheet.Cells(i).Value = ("%i clusters" % i)
	    nb_line = len(container[method][i])
	    if nb_line > iMax:
	    	iMax = nb_line

	    for j in range(nb_line):
			excel.ActiveSheet.Cells(j+2,i).Value = container[method][i][j]
	
	# charts generation
	excel.Range("B2:%s%i" % (letter[max(container[method].keys())],iMax)).Select()
	
	# Add a chart
	excel.Charts.Add()

	xlLineMarkers = 65
	xlPieExploded = 69
	excel.ActiveChart.ChartType = xlLineMarkers
	
	# Cree un titre
	excel.ActiveChart.HasTitle = 1
	excel.ActiveChart.ChartTitle.Characters.Text = "Results for the %i-th method" % method



# container[method] = { 1 : list[K=1] ; 2 : list[K=2] ; etc. }
container[1] = {}
container[2] = {}

for f in os.listdir(path):
	if os.path.isfile(os.path.join(path, f)) and name.match(f, re.I):
		s=sult.search(f).groups()
		print "Parsing... ", f, " for ", s, " optimization"
		parse(path + "/" + f,s)
		"""
		print "printing dictionnary:"
		print container
		print ""
		print ""
		"""

print "Print info about results files"
print "Number of methods = %i" % len(container.keys())
k = 1
while k <= len(container.keys()):
	print "Number of observation in the %i-th method: %i" % (k, len(container[k]))
	k += 1

#debug afficher au hasard la list [2][8]
#print container[2][8]



showExcel(1)
showExcel(2)


