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 dir_build(dir_path):
    cmd = f'mkdir -p {dir_path}'
    returncode, sout, serr = runCmd(cmd)
    print(cmd)
    final_result = ""
    if returncode != 0:
        final_result = serr.decode("gbk")
    return returncode, final_result

def DrawPhas(input_file,input_file_sorted,phaseLen,outFormat,trigger_info,output_dir,sRNAminer):
    n = 0
    if not output_dir.endswith("/") or output_dir.endswith("\\"):
        output_dir = output_dir + "/"
    final_path = output_dir + "PHASLocus_Graph/"
    while os.path.exists(final_path):
        n += 1
        final_path = output_dir + "PHASLocus_Graph_" + str(n) + "/"
    output_dir = final_path
    returncode, final_result = dir_build(output_dir)
    folder_path = os.path.dirname(os.path.abspath(input_file_sorted))
    input_sorted = os.path.basename(os.path.abspath(input_file_sorted))
    PHAStmp = output_dir + "PHAS_list.tmp"
    tmp_file = open(PHAStmp,"w+")
    add_content_list = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", input_sorted]
    add_content = "\t".join(add_content_list)
    phas_file_content = open(input_file, "r")
    while True:
        line = phas_file_content.readline().rstrip()
        if not line:break
        final_add_content = line + "\t" + add_content
        print(final_add_content,file=tmp_file)

    tmp_file.close()

    cmd = ""
    if trigger_info == "":
        cmd = f'java -cp "{sRNAminer}" biocjava.sRNA.Miner.phasiRNA.PHASMergedListToGraphAdvanced --inPhasList "{PHAStmp}"' + \
              " --phasLen " + str(phaseLen) + " --inDir " + folder_path + " --outDir " + output_dir +" --outFormat " + \
              outFormat + "  --normLibSize 20000000"
    elif trigger_info != "":
        cmd = f'java -cp "{sRNAminer}" biocjava.sRNA.Miner.phasiRNA.PHASMergedListToGraphAdvanced --inPhasList "{PHAStmp}"' + \
              " --phasLen " + str(phaseLen) + " --inDir " + folder_path + " --outDir " + output_dir + " --outFormat " + \
              outFormat + "  --normLibSize 20000000" + " --trigerInfo " + trigger_info
    returncode, sout, serr = runCmd(cmd)
    os.remove(PHAStmp)
    if returncode == 0:
        final_result = sout.decode("gbk")
    else:
        final_result = serr.decode("gbk")

    return returncode,final_result

def DrawPHAS_pipeline(input_file,input_file_sorted,phaseLen,outFormat,trigger_info,output_dir,sRNAminer):
    print("Start...")
    returncode, final_result = DrawPhas(input_file,input_file_sorted,phaseLen,outFormat,trigger_info,output_dir,sRNAminer)
    print(final_result)
    if returncode == 0:
        print("Finish!")