import pyfits
import os,sys
import time

# return  [min,max]  entre les longeur d onde xmin,xmax
def foundMinMax(data,start,step,xmin,xmax):
	ixmin=int((xmin-start)/step)
	ixmax=int((xmax-start)/step)
	n=len(data)
	if (ixmin<0):
		ixmin=0
	if (ixmax<0):
		ixmax=0
	if (ixmin>=n):
		ixmin=0
	if (ixmax>=n):
		ixmax=n
	return [min(data[ixmin:ixmax]),max(data[ixmin:ixmax])]

def WriteDatFile(data,start,step):
	f=open(PathFileTmpDat,'w')
	wave=start
	for intensity in data:
		l=str(wave)+" "+str(intensity)+"\n"
		f.write(l)
		wave+=step
	f.close()
	
def WritePngFile(DstFile,title,xmin,xmax,ymin,ymax):
	print("DstFile: "+DstFile)
	print("Title: "+title)

	f=open(PathGnuplot+'gnuplotcmd.txt','w')
	l1="call 'C:\\\\gnuplot\\\\std.gnu' '"+PathFileTmpDat+"' '"+title+"' '"
	l1+=str(xmin)+":"+str(xmax)+"' '"+str(ymin)+":"+str(ymax)+"' '1600,400' '"+DstFile+"'\n"
	l2="pause -1"
	f.write(l1)
#	f.write(l2)
	f.close()

	cmd=PathGnuplot+"binary\\pgnuplot.exe C:\gnuplot\gnuplotcmd.txt"
	print ("CMD = "+cmd)
	sortie=os.system(cmd)
	print(sortie)

# verifie le nombre d'argument
if len(sys.argv)==2:
        filename=sys.argv[1]
        print "nom de fichier: "+filename
else:
        print "nombre d'argument incorrect"
        print "utiliser un arguments 'nom fichier'"
        exit(1)
	
BasePath=sys.path[0].replace("\\","\\\\")+"\\\\"
dbSourcePath=BasePath+"web-"+filename
PathWeb=BasePath+"web-"+filename+"\\\\"
PathFileTmpDat=BasePath+"@.dat"

PathGnuplot="C:\\gnuplot\\"
WebPageFileName="auto-"+filename+".html"
WebTitle="Spectroscopic observation of "+filename

dirList= os.listdir(dbSourcePath)
dirList=sorted(dirList)
#efface les fichier .png present
for file in dirList:
	if (file.endswith(".png")):
		print "remove " + file
		os.remove(dbSourcePath+"\\"+file)


f=open(PathWeb+WebPageFileName,'w')
f.write("<html>\n<head>\n<title>"+WebTitle+"</title>\n")
f.write("""<meta http-equiv="content-type" content=" Text / html; Charset = ISO - 8859 - 1">""")
f.write("</head>\n<body>\n")
f.write("<H1>"+WebTitle+"</H1>\n")
f.write("Page genere automatiquement le "+time.strftime("%d/%m/%Y a %H:%M")+" par un script python a partir des fichiers fits au format definit pour la base de donnee Bess<br>")
f.write("Auteur Thierry Lemoult, pour m ecrire: thierry  dot  lemoult  arobase  gmail dot com<br>\n")


# tri des fichiers suivant la date d'observation
ListOrder=[]
for file in dirList:
	if (file.endswith(".fits") or file.endswith(".fit")):
		hdulist = pyfits.open(dbSourcePath+'/'+file)
		prihdr  = hdulist[0].header
		ListOrder=ListOrder+[(file,prihdr['OBJNAME']+prihdr['DATE-OBS'])]
ListOrder=sorted(ListOrder,key=lambda ListOrder:ListOrder[1])
dirList=[a[0] for a in ListOrder]
# fin du tri des fichiers


# creer un tableau resumant les observations
f.write("""<table border="1"cellpadding="0"cellspacing="1">\n""")
f.write("<tr><td>Objet</td><td>date</td><td>Pose</td><td>Instrument</td><td>fichier</td></tr>\n")
for file in dirList:
	hdulist = pyfits.open(dbSourcePath+'/'+file)
	prihdr  = hdulist[0].header
	try:
		exptime2=prihdr['EXPTIME2']
		if (exptime2==''):
			try:
				exptime2=str(prihdr['EXPTIME'])+"s"
			except KeyError:
				exptime2='undefine'
	except KeyError:
                try:
                        exptime2=str(prihdr['EXPTIME'])+"s"
                except KeyError:
                        exptime2='undefine'
	print "exptime2=" + str(exptime2)
	try:
		instrument=prihdr['BSS_INST']
	except KeyError:
		instrument=''
	
	f.write("<tr><td>"+prihdr['OBJNAME']+"</td><td>"+prihdr['DATE-OBS']+"</td><td>"+exptime2+"</td><td>"+instrument+"</td><td><a href=\""+file+"\">"+file+"</a></td><tr>\n")
f.write("</table><p>\n")


#genere les graphiques	
f.write("""<table border="1"cellpadding="0"cellspacing="10">\n""")
i=0  #index unique pour les nom de fichier
for file in dirList:
	print "File name: "+file
	hdulist = pyfits.open(dbSourcePath+'/'+file)
	prihdr  = hdulist[0].header
	name=prihdr['OBJNAME']
	dateObs=prihdr['DATE-OBS']
	try:
		Instrument=prihdr['BSS_INST']
	except KeyError:
		Instrument='not define'
	
	try:
		exptime2=prihdr['EXPTIME2']
		if (exptime2==''):
			try:
				exptime2=str(prihdr['EXPTIME'])+"s"
			except KeyError:
				exptime2='undefine'
	except KeyError:
		try:
			exptime2=str(prihdr['EXPTIME'])+"s"
		except KeyError:
			exptime2='undefine'
	
	try:
		resolStr=str(prihdr['BSS_ITRP'])
		
	except KeyError:
		resolStr="non definie"
		
	start=prihdr['CRVAL1']
	step=prihdr['CDELT1']
	nstep=prihdr['NAXIS1']
	print "longueur d onde [" + str(start) + " ... " +str(start+step*nstep)+"] "+prihdr['CUNIT1']
	print "************"

	f.write("<tr><td>")
	f.write("<h3>"+name+"</h3>")
	f.write("<ul><li>Date: "+dateObs[0:10]+" a "+dateObs[11:13]+"h"+dateObs[14:16]+" TU</li>")
	f.write("<li>Temps de pose: "+exptime2+"</li>")
	f.write("<li>Instrument:"+Instrument+"</li>")
	f.write("<li>Resolution typique: "+resolStr+"</li>")
        try:
                Site=prihdr['BSS_SITE']
        except KeyError:
                Site='undefined'
	f.write("<li>Site: "+Site+"</li></ul>")
	f.write("<p>Le spectre a telecharger:<br><a href=\""+file+"\">"+file+"</a></td>")
	f.write("<td>")

	
	WriteDatFile(hdulist[0].data,start,step)	
	titre=name+"   "+dateObs[0:10]+" "+dateObs[11:22]+"  "+Instrument+"  "+exptime2
	
	if (nstep*step>1000):  # si on couvre une large bande spectral, on fait des zoom...
		graph=[[start+step*nstep/2.0,step*nstep/2.0,""],[6560,60,"Region Ha"],[4860,60,"Region Hb"],[5250,250,"Region Fe"],[5885,55,"Region HeI-Fe"],[6676,20,"Region HeII"],[4040,200,"region Ca"]]
#		graph=[[start+step*nstep/2.0,step*nstep/2.0,""],[6560,60,"Region Ha"]]
	else: # sinon on affiche juste tout le spectre
		graph=[[start+step*nstep/2.0,step*nstep/2.0,""]]
	
	
	for zoom in graph:
		i+=1
		lmin=zoom[0]-zoom[1]
		lmax=zoom[0]+zoom[1]
		regionTitle=zoom[2]
		if (lmin>=start*0.98 and lmax<=(start+step*nstep)*1.02):
			[Imin,Imax]=foundMinMax(hdulist[0].data,start,step,lmin,lmax)
			pngFileName=name+"_"+dateObs[0:10]+"_"+dateObs[11:13]+"h"+dateObs[14:16]+"m_"+regionTitle+"_"+str(i)+".png"
			WritePngFile(PathWeb+pngFileName,titre+" "+regionTitle,lmin,lmax,Imin,Imax)
			f.write("<img src = \""+pngFileName+"\" border=\"0\">")

	f.write("</td></tr>\n")

# ferme le fichier html
f.write("</table></body>\n</html>\n")	
f.close()
	
