import os
import subprocess
import sys

#print("output: "+sys.argv[1])
#print("video: "+sys.argv[2])
#print("timeFrom: "+sys.argv[3])
#print("timeTo: "+sys.argv[4])
#print("TRA here: "+sys.argv[5])

if(len(sys.argv.__str__().split()) < 8):	# First parameter calls this function
	sys.exit("There should be at least 7 parameters:\n1. Path Fiji binary\n2. Output Folder\n3. Video Name\n4. Time From\n5. Time To\n6. TRA Folder\n7. Input Folder 1\n8. Input Folder 2\n9. ...")

inputFolders=[]
for i in range(7,len(sys.argv)):
   inputFolders.append(sys.argv[i])

#print(["INPUTS here: ",inputFolders])
# list of input folders with participants' segmentations
#inputFolders = ["C:/testing/01_RES-01",
#                "C:/testing/01_RES-14"]
fijiBinary = sys.argv[1]
outputFolder = sys.argv[2]	# into this folder, all outputs should be generated
videoname = sys.argv[3]
timefrom = sys.argv[4]
timeto = sys.argv[5]
gtFolder = sys.argv[6]		# folder with tracking markers

N = len(inputFolders)
#N=0 -- 000000000001 == 1 << 0
#N=1 -- 000000000010 == 1 << 1
#N=2 -- 000000000100 == 1 << 2
#N=3 -- 000000001000 == 1 << 3
#N=4 -- 000000010000 == 1 << 4

# the combinations sampling happens here
# the current combination is stored in the array of paths: inFolders
for j in range(1, 2**N):		# examine combination, bit by bit from the right
	inFolders = []
	for i in range(0,N):
		if (j & (1 << i)) > 0:	# if i-th bit is 1, then add inputFolders[i]
			inFolders.append(inputFolders[i])

	Nfol = len(inFolders)
	# this goes over all possible thresholds given there is N input segmentations
	for T in range(1, Nfol+1):
		# non-colliding name of the output folder + create it
		outFolder = outputFolder + "/merged_" + videoname + "_" + str(j).zfill(5) + "_T=" + str(T)
		if(not os.path.isdir(outFolder)):
			os.makedirs(outFolder)
		# create the job.txt in this folder
		jobFile = open(outFolder+"/job.txt","w")
		# add the current input folders into the job.txt
		for I in inFolders:
			jobFile.write(I + "/maskXXX.tif\n")

		# also add the path to the tracking markers into the job.txt + close the file
		jobFile.write(gtFolder + "/TRA/man_trackXXX.tif")
		jobFile.close()

		print("Prepared " + outFolder)
		# run the Annotations merging tool, with these parameters:
		# job: outFolder+"/job.txt", threshold: T, output: outFolder
		subprocess.call(fijiBinary +" --headless --run \"Annotations Merging Tool\"  \"mergeModel=\\\"Threshold - flat weights\\\",filePath=\\\"" + outFolder + "/job.txt\\\",mergeThreshold=" + str(
									 T) + ",fileIdxFrom=" + str(timefrom) + ",fileIdxTo=" + str(timeto) + ",outputPath=\\\"" + outFolder + "/maskXXX.tif\\\"\"", shell=True)

		subprocess.call(fijiBinary +" --headless --run \"Technical measures\" \"resPath=\\\"" + outFolder + "\\\",gtPath=\\\"" + gtFolder + "\\\",calcSEG=true,calcTRA=false,optionVerboseLogging=true,optionConsistency=false\"", shell=True)