import argparse
import traceback
from sRNA_abundance import calculate_alignments_read
import os
def detInfo(mappingLines):
    lines = mappingLines.split('\n')
    posDetInfo = {}
    for line in lines:
        if line == "": continue
        (readid, seq, chrom, start, end, abund, strand, hits) = line.split('\t')
        if len(seq) not in posDetInfo:  # read abundance to each position
            posDetInfo[len(seq)] = int(abund) / int(hits)
        else:
            posDetInfo[len(seq)] += int(abund) / int(hits)

    for length in range(20, 25):  # assign a value to each read length
        if length not in posDetInfo:
            posDetInfo[length] = 0

    return (posDetInfo)



def ReadmappingFile(mappingFile):
    FILE = open(mappingFile, "r")
    pos2abund = {}
    while True:  # group together the mapping lines with the same chromosomal position
        line = FILE.readline().rstrip()
        if not line: break
        eles = line.split('\t')
        start_pos = str(int(eles[3]) + 1)
        if eles[2] not in pos2abund:
            pos2abund[eles[2]] = {}
            if start_pos not in pos2abund[eles[2]]:
                pos2abund[eles[2]][start_pos] = line + "\n"
            else:
                pos2abund[eles[2]][start_pos] += line + "\n"
        else:
            if start_pos not in pos2abund[eles[2]]:
                pos2abund[eles[2]][start_pos] = line + "\n"
            else:
                pos2abund[eles[2]][start_pos] += line + "\n"

    FILE.close()
    return pos2abund
def calSRNAabun(sRNAloci_file,mappingFile,normNum):
    sRNAloci_dict = {}
    pos2abund = ReadmappingFile(mappingFile)
    sRNAloci_file_content = open(sRNAloci_file,"r")
    while True:
        sRNA_line = sRNAloci_file_content.readline().rstrip()
        if not sRNA_line:break
        if sRNA_line.startswith("sRNAloci_ID\tChr_ID\tStart_Pos"):
            continue
        else:
            Total_abun = 0
            sRNA_line_eles = sRNA_line.split('\t')
            lenAbund = {}
            sRNAloci_ID = sRNA_line_eles[0]
            Chr_ID = sRNA_line_eles[1]
            Start_Pos = sRNA_line_eles[2]
            End_Pos = sRNA_line_eles[3]
            for pos in range(int(Start_Pos), int(End_Pos)):
                if Chr_ID in pos2abund:
                    if str(pos) in pos2abund[Chr_ID]:  # the key of this dict is a string, so add str() to pos
                        posInfo = detInfo(pos2abund[Chr_ID][str(pos)])
                        for readLen in range(20, 25):
                            if readLen not in lenAbund:
                                lenAbund[readLen] = posInfo[readLen] * 10000000 / int(normNum)  # initiate a value to the dict
                            else:
                                lenAbund[readLen] += posInfo[readLen] * 10000000 / int(normNum)
            for m in range(20, 25):
                if m not in lenAbund.keys():
                    lenAbund[m] = 0
                Total_abun += lenAbund[m]
            lenAbund["Total"] = Total_abun
            sRNAloci_dict[sRNAloci_ID + "-" + Chr_ID + "-" + Start_Pos + "-" + End_Pos] = lenAbund
    sRNAloci_file_content.close()
    return sRNAloci_dict

def main(sRNAloci_file,input_file_1,output_file,Batch_mode):
    print("Start...")
    try:
        if Batch_mode:
            input_file_content = open(input_file_1, "r")
            file_list_1 = [i.strip() for i in input_file_content.readlines()]
            input_file_content.close()
            file_list = []
            sRNAloci_expression_total_dict = {}
            output_file_content = open(output_file,"w+")
            for file in file_list_1:
                file_list.append(os.path.basename(file))
                norm_num = calculate_alignments_read.cal_abundance(file)
                print("start calculate:" + file)
                sRNAloci_dict = calSRNAabun(sRNAloci_file, file,norm_num)
                print("calculate finish:" + file)
                sRNAloci_expression_total_dict[file] = sRNAloci_dict
            sRNAloci_file_content = open(sRNAloci_file,"r")
            file_list_fit_table = []
            for i in file_list:
                file_list_fit_table.append(i)
                file_list_fit_table.append(" ")
                file_list_fit_table.append(" ")
                file_list_fit_table.append(" ")
            file_name = "\t".join(file_list_fit_table)
            length_str = "\t21nt\t22nt\t23nt\t24nt" * len(file_list)
            print(" \t \t \t \t" + file_name, file=output_file_content)
            print("sRNAloci_ID\tChrID\tStart_Pos\tEnd_Pos" + length_str, file=output_file_content)
            while True:
                line = sRNAloci_file_content.readline().rstrip()
                if not line:break
                if line.startswith("sRNAloci_ID\tChr_ID\tStart_Pos"):
                    continue
                else:
                    line_signal = 0
                    sRNA_line_eles = line.split("\t")
                    sRNAloci_ID = sRNA_line_eles[0]
                    Chr_ID = sRNA_line_eles[1]
                    Start_pos = sRNA_line_eles[2]
                    End_pos = sRNA_line_eles[3]
                    sRNAloci_search_key = sRNAloci_ID + "-" + Chr_ID + "-" + Start_pos + "-" + End_pos
                    for file in file_list:
                        if line_signal == 0:
                            print(sRNAloci_ID,Chr_ID,Start_pos,End_pos,round(sRNAloci_expression_total_dict[file][sRNAloci_search_key][21],2),
                                  round(sRNAloci_expression_total_dict[file][sRNAloci_search_key][22],2),
                                  round(sRNAloci_expression_total_dict[file][sRNAloci_search_key][23],2),
                                  round(sRNAloci_expression_total_dict[file][sRNAloci_search_key][24],2),sep="\t",end= "\t", file=output_file_content)
                            line_signal += 1
                        else:
                            print(round(sRNAloci_expression_total_dict[file][sRNAloci_search_key][21],2),
                                  round(sRNAloci_expression_total_dict[file][sRNAloci_search_key][22],2),
                                  round(sRNAloci_expression_total_dict[file][sRNAloci_search_key][23],2),
                                  round(sRNAloci_expression_total_dict[file][sRNAloci_search_key][24],2), sep="\t", end="\t",
                                  file=output_file_content)
                    print("\n",end="",file=output_file_content)
                    # sRNAloci_Total_list = []
            sRNAloci_file_content.close()
            output_file_content.close()
        else:
            file_list_1 = str(input_file_1).split(",")
            file_list = []
            sRNAloci_expression_total_dict = {}
            output_file_content = open(output_file, "w+")
            for file in file_list_1:
                file_list.append(os.path.basename(file))
                norm_num = calculate_alignments_read.cal_abundance(file)
                print("start calculate:" + file)
                sRNAloci_dict = calSRNAabun(sRNAloci_file, file, norm_num)
                print("calculate finish:" + file)
                sRNAloci_expression_total_dict[file] = sRNAloci_dict
            sRNAloci_file_content = open(sRNAloci_file, "r")
            file_list_fit_table = []
            for i in file_list:
                file_list_fit_table.append(i)
                file_list_fit_table.append(" ")
                file_list_fit_table.append(" ")
                file_list_fit_table.append(" ")
            file_name = "\t".join(file_list_fit_table)
            length_str = "\t21nt\t22nt\t23nt\t24nt" * len(file_list)
            print(" \t \t \t \t" + file_name, file=output_file_content)
            print("sRNAloci_ID\tChrID\tStart_Pos\tEnd_Pos" + length_str, file=output_file_content)
            while True:
                line = sRNAloci_file_content.readline().rstrip()
                if not line: break
                if line.startswith("sRNAloci_ID\tChr_ID\tStart_Pos"):
                    continue
                else:
                    line_signal = 0
                    sRNA_line_eles = line.split("\t")
                    sRNAloci_ID = sRNA_line_eles[0]
                    Chr_ID = sRNA_line_eles[1]
                    Start_pos = sRNA_line_eles[2]
                    End_pos = sRNA_line_eles[3]
                    sRNAloci_search_key = sRNAloci_ID + "-" + Chr_ID + "-" + Start_pos + "-" + End_pos
                    for file in file_list:
                        if line_signal == 0:
                            print(sRNAloci_ID, Chr_ID, Start_pos, End_pos,
                                  round(sRNAloci_expression_total_dict[file][sRNAloci_search_key][21], 2),
                                  round(sRNAloci_expression_total_dict[file][sRNAloci_search_key][22], 2),
                                  round(sRNAloci_expression_total_dict[file][sRNAloci_search_key][23], 2),
                                  round(sRNAloci_expression_total_dict[file][sRNAloci_search_key][24], 2), sep="\t",
                                  end="\t", file=output_file_content)
                            line_signal += 1
                        else:
                            print(round(sRNAloci_expression_total_dict[file][sRNAloci_search_key][21], 2),
                                  round(sRNAloci_expression_total_dict[file][sRNAloci_search_key][22], 2),
                                  round(sRNAloci_expression_total_dict[file][sRNAloci_search_key][23], 2),
                                  round(sRNAloci_expression_total_dict[file][sRNAloci_search_key][24], 2), sep="\t",
                                  end="\t",
                                  file=output_file_content)
                    print("\n", end="", file=output_file_content)
                    # sRNAloci_Total_list = []
            sRNAloci_file_content.close()
            output_file_content.close()
        print("Finish!")
    except Exception as e:
        print(e)



if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--input_file','-i',required=True,help="Set a list of bowtie File [sorted] [Required]")
    parser.add_argument('--sRNAloci_file',required=True, help="ID\tChr\tStart\tEnd [Required]")
    parser.add_argument('--Batch_mode',action='store_true',help="Bulk sample")
    parser.add_argument('--output_file','-o',required=True,help="File for output [Required]")
    args = parser.parse_args()
    main(args.sRNAloci_file,args.input_file,args.output_file,args.Batch_mode)
