import sys , os
sys.path.append("../../src/lines")

import lineTools as lt
import pickle
import matplotlib.pyplot as pl

### working dir. and files
wd = "/home/stephane/Science/RadioGalaxy/ALMA/absorptions/analysis/a/"
os.chdir(wd)

datadir   = "dataSpecAll/"
dbline    = "lineAll.db"
transfile = "splatalogue.csv"
dirplot   = "plots/"

"""
Explanation: Method to try to match lines, mainly in absorption, with known lines at different redshift. The lineid musr be identified first to discard wrong detections.
End of explanation
"""


def outputMatch(matches, minmatch = 5, mainLines = None):

    for m in matches:
        imax = len(m)
        ifound = 0

        redshift = m[0]
        
        for i in range(1,len(m)):
            if len(m[i]) > 0:
                    ifound += 1
                    
        if mainLines != None:
            ifound =0
            for i in range(1,len(m)):
                    for mainline in mainLines:
                        if len(m[i]) > 0:
                            for line in m[i]:
                                if line[0].find(mainline) != -1:
                                    ifound += 1
        
        if ifound >= minmatch:
            print("########################")
            print("## Redshift: %f"%(redshift))
            print("## Freq. matched: %d"%(ifound))
            print("##")
            print("## Formula Name E_K Frequency")
            print("##              (K)   (MHz)")
            for i in range(1,len(m)):
                if len(m[i]) > 0:
                    print("## Line:")
                    for line in m[i]:
                        print line
        
            print("##      \n###END###\n")

source =  "J2148+0657"
redshift = 0.895

al = lt.analysisLines(dbline)
cmdsql = "select lineid FROM lines WHERE source = '%s'"%(source)
resdb = al.query(cmdsql)
lineid = []
for l in resdb:
    lineid.append(l[0])
print(lineid)

"""
Explanation: We define the source to be scanned from the lineAll.db
End of explanation
"""


m = al.scanningSplatRedshiftSourceLineid(lineid, zmin = redshift , zmax = 0.90, dz = 1e-4,nrao = True, emax= 40., absorption = True, emission = True )

redshift = []
lineDetected =[]
minmatch = 15

for l in m:
    redshift.append(l[0])
    
    ifound = 0
    
    for i in range(1,len(l)):
        if len(l[i]) > 0:
            ifound += 1
            
    if ifound >= minmatch:
        print("###Redshift: %f"%(l[0]))
        print("##")
        for line in l[1:-1]:
            if len(line) > 0:
                print line
        print("\n\n")
    
    
    lineDetected.append(ifound)

"""
Explanation: Scan through the lines (lineid) matching with a local splatalogue.db. emax is the maximum energy of the upper level to restrain to low energy transitions...
End of explanation
"""


pl.figure(figsize=(15,10))
pl.xlabel("z")
pl.ylabel("Lines")
pl.plot(redshift, lineDetected, "k-")
pl.show()


## uncomment to save data in a pickle file
f = open("3c273-redshift-hires-scan.pickle","w")
pickle.dump(m,f )
f.close()


"""
Explanation: Plot the detected lines vs. the redshift.
End of explanation
"""


mL = ['CO v=0','HCN','HCO+']
outputMatch(m, minmatch=3, mainLines = None)

"""
Explanation: Display the matching transitions
End of explanation
"""


