import analysis
import sys
import os
import getData
import json
import config
import segmentation


def main(configFile):
   with open(configFile,'r') as f:
      xsetup=json.load(f)
   db,fb=getData.connectDB(xsetup['network'])

   qfilter=config.getFilter(xsetup)
   
   rows=getData.getPatients(db,xsetup,qfilter)

   mode=['global','IVF']
   for r in rows:
      segmentation.loadSegmentation(db,fb,r,xsetup)
      getData.downloadCenters(fb,r,xsetup)
      for m in mode:
         getData.downloadFitParFinal(fb,r,xsetup,m)

   pixelFitMode='IVF'
   for r in rows:
      code=config.getCode(r,xsetup)
      nc=segmentation.getNC(r,xsetup)
      for s2 in xsetup['sigma2']:
         files=config.printPixelFitParFinalRowNames(r,xsetup,nc,s2,pixelFitMode)
         fullFiles=[getData.getLocalPath(r,xsetup,f) for f in files]
         filesPresent=[os.path.isfile(f) for f in fullFiles]
         #check if we need to run analysis
         if not all(filesPresent):
            analysis.doPixelAnalysisRow(r,xsetup)

         getData.copyToServer(fb,r,xsetup,files)
      #
      #getData.uploadPixelFitParFinal(fb,r,xsetup,pixelFitMode)


if __name__=="__main__":
   main(sys.argv[1])
