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 remove_rRNA(input_fasta,thread,dir_path,rRNA_file):
    returncode = 0
    try:
        if os.path.exists(input_fasta):
            if os.path.exists(rRNA_file):
                prefix,_ = os.path.splitext(input_fasta)
                output_fasta = dir_path + os.path.basename(prefix) + ".no_rRNA.fa"
                output_Rfam_log = output_fasta + ".rfam.log"
                cmd = f'bowtie -v 1 -f -p {thread} {rRNA_file} {input_fasta} --un {output_fasta} 1>/dev/null 2>{output_Rfam_log}'

                returncode, sout, serr = runCmd(cmd)
                if returncode == 0:
                    final_result = sout.decode("gbk")
                else:
                    final_result = serr.decode("gbk")
            else:
                returncode += 1
                final_result = f'File Not Found:{rRNA_file}'
        else:
            returncode += 1
            final_result = f'File Not Found:{input_fasta}'
        return returncode,final_result
    except Exception:
        returncode += 1
        final_result = traceback.format_exc()
        return returncode,final_result


def remove_Organelle(input_fasta,thread,dir_path,organelle_file):
    returncode = 0
    try:
        if os.path.exists(input_fasta):
            if os.path.exists(organelle_file):
                prefix,_ = os.path.splitext(input_fasta)
                output_fasta = dir_path + os.path.basename(prefix) + ".no_ol.fa"
                output_organelle_log = output_fasta + ".organelle.log"
                cmd = f'bowtie -v 1 -f -p {thread} {organelle_file} {input_fasta} --un {output_fasta} 1>/dev/null 2>{output_organelle_log}'

                returncode, sout, serr = runCmd(cmd)
                if returncode == 0:
                    final_result = sout.decode("gbk")
                else:
                    final_result = serr.decode("gbk")
            else:
                returncode += 1
                final_result = f'File Not Found:{organelle_file}'
        else:
            returncode += 1
            final_result = f'File Not Found:{input_fasta}'
        return returncode,final_result
    except Exception:
        returncode += 1
        final_result = traceback.format_exc()
        return returncode,final_result

def quality_control_merger_pipeline(input_file_1,thread,dir_path,organelle_file,rRNA_file,Batch_mode):
    print("Start...")
    returncode = 0
    final_result = ""
    if not dir_path.endswith("/") or dir_path.endswith("\\"):
        dir_path = dir_path + "/"
    log_file = dir_path + "Quality_Control.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 = remove_rRNA(input_file,thread,dir_path,rRNA_file)
            print(final_result,file=log_file_content)
            if returncode == 0:
                print(final_result)
                prefix, _ = os.path.splitext(input_file)
                input_file = dir_path + os.path.basename(prefix) + ".no_rRNA.fa"
                returncode,final_result = remove_Organelle(input_file,thread,dir_path,organelle_file)
                if returncode != 0:
                    break
            else:
                break
        print(final_result)
        input_file_content.close()
    else:
        file_list = str(input_file_1).split(",")
        for input_file in file_list:
            returncode, final_result = remove_rRNA(input_file, thread, dir_path, rRNA_file)
            print(final_result, file=log_file_content)
            if returncode == 0:
                print(final_result)
                prefix, _ = os.path.splitext(input_file)
                input_file = dir_path + os.path.basename(prefix) + ".no_rRNA.fa"
                returncode, final_result = remove_Organelle(input_file, thread, dir_path, organelle_file)
                if returncode != 0:
                    break
            else:
                break
        print(final_result)
    log_file_content.close()
    if returncode == 0:
        print("Finish!")