import subprocess
import argparse
import os
import traceback

def runCmd(cmd):
    res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    sout, serr = res.communicate()
    return res.returncode, sout, serr

def seq_collapse(input_file,dir_path,sRNAminer):
    returncode = 0
    final_result = ""
    try:
        prefix,_ = os.path.splitext(input_file)
        output_file = dir_path + os.path.basename(prefix) + ".mc.fa"
        cmd = f'java -cp "{sRNAminer}" biocjava.sRNA.Tools.sRNAseqCollasper --inFx "{input_file}" --outCollaspedFa "{output_file}"'

        returncode, sout, serr = runCmd(cmd)
        if returncode == 0:
            final_result = "Collapse data Finish!"
        else:
            final_result = serr.decode("gbk")
        return returncode, final_result
    except Exception:
        returncode += 1
        final_result = traceback.format_exc()
    return returncode, final_result

def seq_collapse_merger_pipeline(input_file_1,dir_path,Batch_mode,sRNAminer):
    print("Start...")
    returncode = 0
    final_result = ""
    if not dir_path.endswith("/") or dir_path.endswith("\\"):
        dir_path = dir_path + "/"
    log_file = dir_path + "Seq_Collapse.log"
    log_file_content = open(log_file, "w+")
    if Batch_mode:
        input_file_content = open(input_file_1, "r")
        file_list = [i.strip() for i in input_file_content.readlines()]
        for input_file in file_list:
            returncode, final_result = seq_collapse(input_file,dir_path,sRNAminer)
            print(final_result,file=log_file_content)
            print(final_result)
            if returncode != 0:
                break
        input_file_content.close()
    else:
        file_list = str(input_file_1).split(",")
        for input_file in file_list:
            returncode, final_result = seq_collapse(input_file, dir_path, sRNAminer)
            print(final_result, file=log_file_content)
            print(final_result)
            if returncode != 0:
                break

    log_file_content.close()
    if returncode == 0:
        print("Finish!")

