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



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)

   for r in rows:
      getData.downloadCenters(fb,r,xsetup)

   mode=['global','IVF']
   tempDir=config.getTempDir(xsetup)


   for r in rows:
      code=config.getCode(r,xsetup)
      for m in mode:
         #check if we need to run analysis
         files=config.printFitParFinalRowNames(r,xsetup,m)
         fullFiles=[os.path.join(tempDir,code,f) for f in files]
         filesPresent=[os.path.isfile(f) for f in fullFiles]
         if not all(filesPresent):
            analysis.doAnalysisRow(r,xsetup,m)
         getData.uploadFitParFinal(fb,r,xsetup,m)
      getData.updateStatus(db,r,xsetup,'doAnalysis')


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