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 TargetSoPipe(input_file,subject_input_file,output_file,Fragment_or_not,Thread,RevCom,e_value,maxMismatch,CutOffScore,sRNAminer):
    cmd = f'java -cp "{sRNAminer}" biocjava.bioDoer.miRNA.TargetSoPipe --inMIRfa '+ input_file +" --inGenomeFa " + subject_input_file + \
          " --outTable " + output_file + " --isFragment " +  str(Fragment_or_not).lower() +" --maxThreadNum " + str(Thread) + \
          " --searchRevCom " + str(RevCom).lower() + " --deleteTmp true --evalue " + str(e_value) + " --maxMisM " + str(maxMismatch) + " --score " + str(CutOffScore)

    returncode, sout, serr = runCmd(cmd)
    if returncode == 0:
        final_result = sout.decode("gbk")
    else:
        final_result = serr.decode("gbk")

    return returncode,final_result

def TargetSoPipe_merger_pipeline(input_file,subject_input_file,output_file,Fragment_or_not,Thread,RevCom,e_value,maxMismatch,CutOffScore,sRNAminer):
    print("Start...")
    returncode, final_result = TargetSoPipe(input_file,subject_input_file,output_file,Fragment_or_not,Thread,RevCom,e_value,maxMismatch,CutOffScore,sRNAminer)
    print(final_result)
    if returncode == 0:
        print("Finish!")
