import os
import subprocess
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 soft_build(input_file,dir_path):
    input_file = os.path.abspath(input_file)
    output_file = dir_path + os.path.basename(input_file)
    print(os.path.splitext(input_file)[-1])
    if os.path.splitext(input_file)[-1] != ".bowtie":
        output_file = dir_path + os.path.basename(input_file) + ".bowtie"
    cmd = f'ln -s {input_file} {output_file}'
    returncode, sout, serr = runCmd(cmd)
    print(cmd)
    if returncode == 0:
        final_result = "Soft Link Build."
    else:
        final_result = serr.decode("gbk")
    return returncode, final_result

def dir_build(dir_path):
    cmd = f'mkdir -p {dir_path}'
    returncode, sout, serr = runCmd(cmd)
    print(cmd)
    if returncode == 0:
        final_result = "Build Dir."
    else:
        final_result = serr.decode("gbk")
    return returncode, final_result

def bowtie_format_change(dir_path,thread,sRNAminer):
    cmd = f'ls {dir_path}*.bowtie| parallel -j {thread} "java -cp {sRNAminer} biocjava.sRNA.Tools.sRNAseqAlignmentFormater --inFile {{}} --outFile {{}}.aln"'
    returncode, sout, serr = runCmd(cmd)
    if returncode == 0:
        final_result = sout.decode('gbk')
    else:
        final_result = serr.decode('gbk')
    return returncode,final_result

def sort_bowtie(dir_path,thread,sRNAminer):
    cmd = f'ls {dir_path}*.bowtie.aln|parallel -j {thread} "java -cp {sRNAminer} biocjava.sRNA.Tools.sRnaAlnIndexBuilder --inAln {{}}"'
    returncode, sout, serr = runCmd(cmd)
    if returncode == 0:
        final_result = sout.decode('gbk')
    else:
        final_result = serr.decode('gbk')
    return returncode,final_result

def convert_bowtie_to_sRNAminer(input_file_1,dir_path,thread,sRNAminer,Batch_mode):
    print("Start...")
    returncode = 0
    n = 0

    if not dir_path.endswith("/") or dir_path.endswith("\\"):
        dir_path = dir_path + "/"
    final_dir_path = dir_path + "Bowtie_to_sRNAminer/"
    while os.path.exists(final_dir_path):
        n += 1
        final_dir_path = dir_path + "Bowtie_to_sRNAminer_" + str(n) + "/"
    dir_path = final_dir_path
    returncode, final_result = dir_build(dir_path)
    print(final_result)
    if returncode == 0:
        log_file = dir_path + "bowtie_to_sRNAminer.log"
        log_file_content = open(log_file, "w+")
        final_result = ""
        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 = soft_build(input_file, dir_path)
                print(final_result, file=log_file_content)
                print(final_result)
                if returncode != 0:
                    break
            if returncode == 0:
                returncode,final_result = bowtie_format_change(dir_path,thread,sRNAminer)
                print(final_result, file=log_file_content)
                print(final_result)
            if returncode == 0:
                returncode,final_result = sort_bowtie(dir_path,thread,sRNAminer)
                print(final_result, file=log_file_content)
            print(final_result)
        else:
            file_list = str(input_file_1).split(",")
            for input_file in file_list:
                returncode, final_result = soft_build(input_file, dir_path)
                print(final_result, file=log_file_content)
                print(final_result)
                if returncode != 0:
                    break
            if returncode == 0:
                returncode, final_result = bowtie_format_change(dir_path, thread, sRNAminer)
                print(final_result, file=log_file_content)
                print(final_result)
            if returncode == 0:
                returncode, final_result = sort_bowtie(dir_path, thread, sRNAminer)
                print(final_result, file=log_file_content)
            print(final_result)
        log_file_content.close()
    if returncode == 0:
        print("Finish!")

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--input_file", "-i",required=True,help="use_for_rfam")
    parser.add_argument('--Batch_mode',action='store_true',help="Bulk sample")
    parser.add_argument("--thread", "-t",required=True,help="use_for_rfam")
    parser.add_argument("--sRNAminer", "-s",required=True,help="use_for_rfam")
    parser.add_argument("--dir_path", "-o",required=True,help="use_for_rfam")
    args = parser.parse_args()
    print("Start analyze")
    convert_bowtie_to_sRNAminer(args.input_file,args.dir_path,args.thread,args.sRNAminer,args.Batch_mode)
    print("Analyze finish!")