import subprocess
import sys
import getopt
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 sRNAloci_identification(input_file,minReadDepth,minRegionGap,dir_path,sRNAminer):
    output_file = dir_path + os.path.basename(input_file) + ".sRNAloci"
    cmd = f'java -cp {sRNAminer} biocjava.sRNA.Miner.sRNAloci.sRNAlociMinerCLI' +  \
          " --inSortedAln " + input_file + " --minReadDepth " + minReadDepth + " --minRegionGap " + minRegionGap + " --outRegionInfo " + output_file
    
    returncode, sout, serr = runCmd(cmd)
    if returncode == 0:
        final_result = sout.decode("gbk")
    else:
        final_result = serr.decode("gbk")
    return returncode,final_result

def sRNAlociMerger_1(dir_path,file_list):
    error_signal = 0
    error_str = ""
    file_list = [os.path.basename(i)+".sRNAloci" for i in file_list]
    try:
        output_file = open(dir_path + "all.sRNAloci.list", "w+")
        for root, dirs, files in os.walk(dir_path):
            for file in files:
                if file in file_list:
                    output_file.write(root + file + "\n")
        output_file.close()

        return error_signal,error_str
    except Exception:
        error_signal += 1
        error_str = traceback.format_exc()
        return error_signal,error_str

def sRNAlociMerger_2(dir_path,sRNAminer):
    input_sRNAloci_list = dir_path + "all.sRNAloci.list"
    Have_sRNAloci_signal = 0
    returncode = 0
    final_result = ""
    try:
        with open(input_sRNAloci_list,"r") as f:
            file_list = [file.rstrip() for file in f.readlines()]
        for file_1 in file_list:
            with open(file_1,"r") as f1:
                content = f1.readlines()
            if len(content) > 1:
                Have_sRNAloci_signal += 1
        if Have_sRNAloci_signal == 0:
            final_result = "No sRNAloci is Found in All Libs!"
            returncode += 1
        else:
            output_sRNAloci_region = dir_path + "all.sRNAloci.region"
            cmd = f'java -cp {sRNAminer} biocjava.sRNA.Miner.sRNAloci.sRNAlociMerger --inFileList ' + input_sRNAloci_list +  \
                  " --outFile " + output_sRNAloci_region

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

def sRNAlociToGff(input_file,dir_path):
    error_signal = 0
    error_str = ""
    try:
        output_file = dir_path + "sRNAloci.gff3"
        input_file_content = open(input_file,"r")
        output_file_content = open(output_file,"w+")
        print("##gff-version 3",file=output_file_content)
        first_line_signal = 1
        n = 1
        while True:
            line = input_file_content.readline().rstrip()
            if not line:break
            if first_line_signal == 1:
                first_line_signal += 1
                continue
            else:
                (sRNAloci_ID, Chr_ID, Start_Pos, End_Pos, TotalAbundance, SpeciesNum, LibNum) = line.split("\t")
                print(Chr_ID, "sRNAminer", "sRNAloci", Start_Pos, End_Pos, ".", ".", ".","ID=" + sRNAloci_ID +
                      ";MaxAbundance=" + str(TotalAbundance) + ";MaxSpecies=" + str(SpeciesNum) +
                      ";libNum=" + str(LibNum),sep="\t",file=output_file_content)
                n += 1
        input_file_content.close()
        output_file_content.close()
        return error_signal, error_str
    except Exception:
        error_signal += 1
        error_str = traceback.format_exc()
        return error_signal, error_str

def sRNAloci_identification_merger_pipeline(input_file_1,minReadDepth,minRegionGap,dir_path,Batch_mode,sRNAminer):
    print("Start...")
    final_result = ""
    returncode = 0
    if not dir_path.endswith("/") or dir_path.endswith("\\"):
        dir_path = dir_path + "/"
    log_file = dir_path + "sRNAloci_identification.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 = sRNAloci_identification(input_file,minReadDepth,minRegionGap,dir_path,sRNAminer)
            print(final_result, file=log_file_content)
            if returncode != 0:
                break
            else:
                print(final_result)

        if returncode == 0:
            returncode,final_result = sRNAlociMerger_1(dir_path,file_list)
            print(final_result, file=log_file_content)
            if returncode == 0:
                print(final_result)
                returncode,final_result = sRNAlociMerger_2(dir_path,sRNAminer)
                print(final_result, file=log_file_content)
                if returncode == 0:
                    print(final_result)
                    returncode, final_result = sRNAlociToGff(dir_path + "all.sRNAloci.region",dir_path)
                    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 = sRNAloci_identification(input_file,minReadDepth,minRegionGap,dir_path,sRNAminer)
            print(final_result, file=log_file_content)
            if returncode != 0:
                break
            else:
                print(final_result)

        if returncode == 0:
            returncode,final_result = sRNAlociMerger_1(dir_path,file_list)
            print(final_result, file=log_file_content)
            if returncode == 0:
                print(final_result)
                returncode,final_result = sRNAlociMerger_2(dir_path,sRNAminer)
                print(final_result, file=log_file_content)
                if returncode == 0:
                    print(final_result)
                    returncode, final_result = sRNAlociToGff(dir_path + "all.sRNAloci.region",dir_path)
                    print(final_result, file=log_file_content)
        print(final_result)

    if returncode == 0:
        print("Finish!")
