from blockbased_synapseaware.makeflow_example.makeflow_helperfunctions import *

from blockbased_synapseaware.benchmark.kimimaro.connectskeletons import ConnectSkeletons

# pass arguments
# read passed arguments
if len(sys.argv) != 2:
    raise ValueError(" Scripts needs exactley 1 input arguments (Prefix) ")
else:
    meta_fp = sys.argv[1]

# read in the data for this block
data = ReadMetaData(meta_fp)

# Redirect stdout and stderr
RedirectOutStreams(data.BlockSize(), "KM", 2, "all", "all", "all")

# check that beforehand step has executed successfully
for iz in range(data.StartZ(), data.EndZ()):
    for iy in range(data.StartY(), data.EndY()):
        for ix in range(data.StartX(), data.EndX()):
            CheckSuccessFile(data.BlockSize(), "KM", 1, iz, iy, ix)

# users must provide an output directory
assert (not data.SkeletonOutputDirectory() == None)
os.makedirs(data.SkeletonOutputDirectory(), exist_ok=True)

# compute the second step to find adjacencies between borders
ConnectSkeletons(data)

# Create and Write Success File
if __name__ == "__main__":

    # read meta filepath
    meta_fp, mf_param_fp, prefix = readArgv(sys.argv)

    # import parameters from file
    import_name = "blockbased_synapseaware.makeflow_example." + mf_param_fp[:-3].replace(
        "/", ".")
    mf_param = importlib.import_module(import_name)

    # read in the data for this block
    data = ReadMetaData(meta_fp)

    # create working directory and directory for temporary makeflow files
    working_dir = data.MFCodeDirectory(
    ) + "/working_directories/{}_working_dir_{:04d}x{:04d}x{:04d}/".format(
        prefix,
        data.BlockSize()[OR_X],
        data.BlockSize()[OR_Y],
        data.BlockSize()[OR_Z])
    temp_file_dir = working_dir + "temp_files/"

    if not os.path.exists(working_dir):
        os.mkdir(working_dir)
    if not os.path.exists(temp_file_dir):
        os.mkdir(temp_file_dir)

    # write pipeline and batch deploy file
    writePipelineFile(working_dir, data, meta_fp, prefix)
    writeBatchFile(working_dir, data)