import subprocess
import argparse
import os
import pandas as pd
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 phasiRNAsQuantify(input_file,phas_info,phasiRNA_length,dir_path,sRNAminer):
    output_file = dir_path + os.path.basename(input_file) + "." + str(phasiRNA_length) +".PHAS.exp"
    cmd = "java -cp " + sRNAminer +" biocjava.sRNA.Miner.phasiRNAsQuantify " \
          "--inAln " + input_file + " --inPHASregion " + phas_info + " --outPhasiRNAExp " + 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 Merge_Exp(file_list,phasiRNA_len,dir_path):
    returncode= 0
    final_result = ""
    try:
        file_list = [os.path.basename(i) + "." + str(phasiRNA_len) +".PHAS.exp" for i in file_list]
        output_file = dir_path + "merged." + str(phasiRNA_len) + ".PHAS.exp.xls"
        EXP_DICT = {}
        for root, dirs, files in os.walk(dir_path):
            for file in files:
                if file in file_list:
                    EXP_DICT[file] = {}
                    sample_name = os.path.basename(file)
                    open_file = open(dir_path + file, "r")
                    while True:
                        line = open_file.readline().rstrip()
                        if not line: break
                        line_list = line.split("\t")
                        EXP_DICT[sample_name][line_list[0]] = line_list[-1]

        data = pd.DataFrame(EXP_DICT)
        data = data.reset_index()
        data = data.rename(columns={"index": "GeneID"})
        data.to_csv(output_file,sep="\t",index=False)
        final_result = "Calculating Finish!"
        return returncode, final_result
    except Exception:
        returncode += 1
        final_result = traceback.format_exc()
        return returncode,final_result

def PHAS_expression_merger_pipeline(input_file_1,phas_info,phasiRNA_length,Batch_mode,dir_path,sRNAminer):
    print("Start...")
    if not dir_path.endswith("/") or dir_path.endswith("\\"):
        dir_path = dir_path + "/"
    log_file = dir_path + "PHAS_Expression.log"
    log_file_content = open(log_file, "w+")
    returncode = 0
    final_result = ""
    if Batch_mode:
        input_file_content = open(input_file_1, "r")
        file_list = [i.strip() for i in input_file_content.readlines()]
        input_file_content.close()
        for input_file in file_list:
            returncode, final_result = phasiRNAsQuantify(input_file,phas_info,phasiRNA_length,dir_path,sRNAminer)
            print(final_result, file=log_file_content)
            if returncode != 0:
                break
        if returncode == 0:
            returncode, final_result = Merge_Exp(file_list,phasiRNA_length,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 = phasiRNAsQuantify(input_file, phas_info, phasiRNA_length, dir_path, sRNAminer)
            print(final_result, file=log_file_content)
            if returncode != 0:
                break
        if returncode == 0:
            returncode, final_result = Merge_Exp(file_list, phasiRNA_length, dir_path)
            print(final_result, file=log_file_content)
        print(final_result)
    log_file_content.close()
    if returncode == 0:
        print("Finish!")