import numpy as np

import PyMca5.PyMcaGui
from  PyMca5.PyMcaGui import MaskImageWidget
import fabio

import sys

import os
import glob

referenceprefix= sys.argv[1]


from  PyQt4 import Qt, QtCore


app=Qt.QApplication([])

def compara_vols(ref ):

    class parInfo:
        LOWBYTEFIRST=1
        s = open(ref+".info").read()
        s=s.replace("!","#")
        exec( s )

    f_ref = open(ref,"r")


    iz = (parInfo.NUM_Z)/2
    

    f_ref.seek( iz*  parInfo.NUM_X*parInfo.NUM_Y * 4    ) 
    sr = f_ref.read( parInfo.NUM_X*parInfo.NUM_Y * 4 )
    
    r  = np.reshape(np.fromstring(sr,"f"), [   parInfo.NUM_Y, parInfo.NUM_X ] )
 
    mostra_slices(r,  ref+" slice %d"%iz)


def compara_edfs(ref  ):
    NN = len( ref)
    iz = NN/2
    print ref
    rname = ref[iz]
    r  = fabio.open(rname).data
    mostra_slices( r,  rname   )


def     mostra_slices( dr, namer,  maskW1 = MaskImageWidget.MaskImageWidget(None , aspect=True,profileselection=True) ):
    from  PyMca5.PyMcaGui import MaskImageWidget

    MaskImageWidget   =  MaskImageWidget.MaskImageWidget

    # maskW1 = MaskImageWidget(None , aspect=True,profileselection=True)

    maskW1.setWindowTitle ( namer )
    maskW1.setImageData(dr  , xScale=(0.0, 1.0), yScale=(0., 1.))
    maskW1.setDefaultColormap(0,0)
    maskW1.plotImage(True)
 
    maskW1.show()
    app.exec_()
    
     
def get_results(radice):
    N=len(radice)
    result={}
    ws=os.walk(radice)
    leafs = [ t[0] for t in ws if len(t[1])==0 ]
    for l in leafs:
        result[l[N:]] = {}
        print l+"/abs.vol"
        result[l[N:]]["vol"] = glob.glob(l+"/*.vol")
        result[l[N:]]["edf"] = glob.glob(l+"/vol*.edf")
    return result

ress_ref = get_results(referenceprefix)
leafs = list(ress_ref.keys())
print leafs
print ress_ref
for l in leafs:
    
    if len(ress_ref[l]["vol"]):
        assert( len(ress_ref[l]["vol"])==1)
        ress_vol = ress_ref[l]["vol"][0]
        compara_vols(ress_vol   )
    elif len(ress_ref[l]["edf"]):
        ress_edf = ress_ref[l]["edf"]
        ress_edf.sort()
        compara_edfs(ress_edf   )
        
    
