import subprocess
import os
import pandas as pd
import traceback
import argparse
from Alignment_Part import alignment
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 adapter_predict_for_use(input_file,sRNAminer):
    cmd = f'java -cp "{sRNAminer}" biocjava.sRNA.Tools.sRNAseqAdapterPrediction --inFq "{input_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 adapter_remove_for_use(input_fasta,output_fasta,adapter,sRNAminer):
    returncode = 0
    try:
        cmd = f'java -cp "{sRNAminer}" biocjava.sRNA.Tools.sRNAseqAdaperRemover --inFxFile "{input_fasta}" --outFaFile "{output_fasta}" --adapter {adapter}'

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

def adapter_treat_merger_pipeline(input_file_1,dir_path,Batch_mode,sRNAminer):
    print("Start...")
    returncode = 0
    final_result = ""
    if not dir_path.endswith("/") or dir_path.endswith("\\"):
        dir_path = dir_path + "/"
    log_file = dir_path + "Adapter_treat.log"
    log_file_content = open(log_file,"w+")
    output_adapter_list = dir_path + "adapter.list"
    output_adapter_list_content = open(output_adapter_list, "w+", encoding='utf-8')
    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 = adapter_predict_for_use(input_file,sRNAminer)
            if returncode == 0:
                print(final_result)
                output_adapter_list_content.write(final_result)
                adapter = final_result.rstrip().split("\t")[1]
                output_file = dir_path + os.path.basename(input_file) + ".trimmed.fa"
                returncode,final_result = adapter_remove_for_use(input_file,output_file,adapter,sRNAminer)
                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 = adapter_predict_for_use(input_file, sRNAminer)
            if returncode == 0:
                print(final_result)
                output_adapter_list_content.write(final_result)
                adapter = final_result.rstrip().split("\t")[1]
                output_file = dir_path + os.path.basename(input_file) + ".trimmed.fa"
                returncode, final_result = adapter_remove_for_use(input_file, output_file, adapter, sRNAminer)
                if returncode != 0:
                    break
            else:
                break
        print(final_result)

    output_adapter_list_content.close()
    if returncode == 0:
        print("Finish!")
