import subprocess
import sys
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 phasiRNA_extract(phas_info,genome_file,phasiRNA_len,output,sRNAminer):
    returncod = 0
    final_result = ""
    tmp_file = phas_info + ".tmp"
    output_tmp_file = open(tmp_file, "w+")
    with open(phas_info,"r") as f:
        for line in f:
            if line.rstrip().startswith("PHASID\tChr_ID\tStart_Pos"):
                continue
            else:
                print(line.rstrip(), file=output_tmp_file)
    output_tmp_file.close()
    cmd = f'java -cp {sRNAminer} biocjava.sRNA.Miner.phasiRNA.PhasiRNASequenceGenerater --inGenome ' + genome_file + \
          " --inPhasResult " + tmp_file + " --outFile " + output + " --phasLen " + phasiRNA_len

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

def phasiRNA_extract_merge_pipeline(phas_info,genome_file,phasiRNA_len,output,sRNAminer):
    print("Start...")
    returncode, final_result = phasiRNA_extract(phas_info,genome_file,phasiRNA_len,output,sRNAminer)
    print(final_result)
    print("Finish!")