import pyfits
import os,sys
import time

#source pour Python 2.7

# recuperer Python 2.7 ici:   http://www.python.org/download/releases/2.7.6/
# attention, il faut garder la coherence entre python et les package. C'est 32 bit ou 63 bit au choix.
# aller ici pour recuperer pyfits:   http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyfits


# 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)+"' '800,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)

# le programme commence ici	
#le repertoire contenant les fichiers .fits au format bess est dans le chemin courant et s apelle   web-xxxxx	
# verifie le nombre d'argument
if len(sys.argv)==2:
        filename=sys.argv[1]
        print "nom du repertoire: "+filename
else:
        print "nombre d'argument incorrect"
        print "utiliser un arguments 'nom de repertoire'"
        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)


#la generation du code html commence ici
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']
	except KeyError:
                try:
                        exptime2=str(prihdr['EXPTIME'])+"s"
                except KeyError:
                        exptime2='undefine'
	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:   # boucle sur les fichiers fits
	#recuperation des mots clef du fichier fits
	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='undefine'
	
	try:
		exptime2=prihdr['EXPTIME2']
	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 "************"

	#genere resume dans la premiere colonne.
	f.write("<tr>\n<td>\n")
	f.write("	<h3>"+name+"</h3>\n")
	f.write("	<ul><li>Date: "+dateObs[0:10]+" a "+dateObs[11:13]+"h"+dateObs[14:16]+" TU</li>\n")
	f.write("	<li>Temps de pose: "+exptime2+"</li>\n")
	f.write("	<li>Instrument:"+Instrument+"</li>\n")
	f.write("	<li>Resolution typique: "+resolStr+"</li>\n")
        try:
                Site=prihdr['BSS_SITE']
        except KeyError:
                Site='undefined'
	f.write("	<li>Site: "+Site+"</li></ul>\n")
	f.write("	<p>Le spectre a telecharger:<br><a href=\""+file+"\">"+file+"</a>\n</td>\n\n")
	

	
	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...
		#definition des bandes a tracer
		graph=[[start+step*nstep/2.0,step*nstep/2.0,""],[4985,40,"Region OIII"],[6560,60,"Region Ha"],[6720,60,"Region SII 6717+6731"], [5461,20,"Polution Hg 5461"],[5780,20,"Polution Hg 5769+5790"],[4700,30,"Region NiI+TiI 4686  Ne 4712"],[7006,30,"Region ArV 7006"],[5876,30,"Region HeI 5876"],[6300,30,"Airglow OI"]]
	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)
			if (Imin<-1):
				Imin=0
			pngFileName=name+"_"+dateObs[0:10]+"_"+dateObs[11:13]+"h"+dateObs[14:16]+"m_"+regionTitle+"_"+str(i)+".png"
			#genere image
			WritePngFile(PathWeb+pngFileName,titre+" "+regionTitle,lmin,lmax,Imin,Imax)
			#insere le lien dans le  html
			f.write("	<td><img src = \""+pngFileName+"\" border=\"0\"></td>\n")

	f.write("</tr>\n\n\n")

# ferme le fichier html
f.write("</table></body>\n</html>\n")	
f.close()
	
