#!/usr/bin/env python

"""
MetaWIBELE: interproscan_signalp_protein_family module
Summary the results of SignalP generated by InterProScan

Copyright (c) 2019 Harvard School of Public Health

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import sys
import os
import os.path
import re
import argparse

try:
	from metawibele import config
	from metawibele import utilities
except ImportError:
	sys.exit("CRITICAL ERROR: Unable to find the MetaWIBELE python package." +
	         " Please check your install.")


# ---------------------------------------------------------------
# Description and arguments
# ---------------------------------------------------------------
description = """
Summary the results of SignalP generated by InterProScan
"""

def get_args ():
	parser = argparse.ArgumentParser(description=description)
	parser.add_argument('-e', "--extension",
	                    help='file extension',
	                    required=True,
	                    default="signalp.signaling.tsv")
	parser.add_argument('-p', "--path",
	                    help='input the path of annotation file',
	                    required=True)
	parser.add_argument('-a', "--method",
	                    help='specify how to assign annotations to families',
	                    choices=["centroid", "consistency"],
	                    required=True,
	                    default="consistency")
	parser.add_argument('-c', "--cluster",
	                    help='input the cluster file for protein families',
	                    default=None)
	parser.add_argument('-o', "--output",
	                    help='output annotation summary file',
	                    required=True)
	values = parser.parse_args()

	return values
# get_args


#==============================================================
# collect cluster info
#==============================================================
def collect_cluster_info (clust_file):  # discovery_cohort.peptides.clust
	cluster = {}
	cluster_mem = {}
	open_file = open(clust_file, "r")
	myclust = ""
	for line in open_file.readlines():
		line = line.strip()
		if not len(line):
			continue
		if re.search("^>", line):
			mym = re.search(">([^;]+)", line)
			myclust = mym.group(1)
			mym = re.search("cluster=([\d]+)", line)
			myclust_id = "Cluster_" + mym.group(1)
			if not myclust in cluster:
				cluster[myclust] = {}
			continue
		mym = re.search("^([\S]+)", line)
		myid = mym.group(1)
		cluster_mem[myid] = myclust + "\t" + myclust_id
		cluster[myclust][myid] = myclust_id
    # foreach line
	open_file.close()
	return cluster, cluster_mem
# function collect_cluster_info


#==============================================================
# collect signaling info
#==============================================================
def collect_signaling_info (cluster_mem, extension, ann_path, outfile):	# split.list
	gram_p = {}
	gram_n = {}
	signals = {}
	signals_n = {}
	signals_p = {}
	#open_list = open(listfile, "r")
	#for samplelist in open_list.readlines():
	filelist = utilities.find_files(ann_path, extension, None)
	for myfile in filelist:
		if not os.path.isfile(myfile):
			config.logger.info ("ERROR! File not exist: " + myfile)
			continue
		open_file = open(myfile, "r")
		titles = {}
		for line in open_file.readlines():
			line = line.strip()
			if not len(line):
				continue
			info = line.split("\t")
			if re.search("^" + utilities.PROTEIN_ID, line):
				for item in info:
					titles[item] = info.index(item)
				continue
			if not info[titles[utilities.PROTEIN_ID]] in cluster_mem:
				continue
			if not info[titles[utilities.PROTEIN_ID]] in signals:
				signals[info[titles[utilities.PROTEIN_ID]]] = {}
			signals[info[titles[utilities.PROTEIN_ID]]][info[titles["Prediction"]]] = ""
			mytype = info[titles["SP"]]
			sample = info[titles[utilities.PROTEIN_ID]]
			sample = re.sub("_[\d]+$", "", sample)
			if mytype == "SignalP_GRAM_POSITIVE":
				signals_p[info[titles[utilities.PROTEIN_ID]]] = info[titles["Prediction"]]
				if not sample in gram_p:
					gram_p[sample] = 0
				gram_p[sample] = gram_p[sample] + 1
			if mytype == "SignalP_GRAM_NEGATIVE":
				signals_n[info[titles[utilities.PROTEIN_ID]]] = info[titles["Prediction"]]
				if not sample in gram_n:
					gram_n[sample] = 0
				gram_n[sample] = gram_n[sample] + 1
		# foreach line
		open_file.close()
	# foreach sample

	# output details for each ORF
	outfile1 = re.sub("_proteinfamilies.", "_proteinfamilies.ORF.", outfile)
	open_out = open(outfile1, "w")
	open_out.write(utilities.PROTEIN_ID + "\ttype\tdetail\tdescription\n")
	for myid in sorted(signals.keys()):
		myinfo = ";".join(signals[myid].keys())
		open_out.write(myid + "\tSignalP_signaling\tSignalP_signaling\t" + myinfo + "\n")
	# foreach seqID
	open_out.close()

	return gram_p, gram_n, signals, signals_p, signals_n
# function collect_signaling_info


#==============================================================
# output info
#==============================================================
def output_info (cutoff, cluster, gram_p, gram_n, signals, signals_p, signals_n, assign_flag, outfile):

	"""
	open_file = open(outfile, "w")
	title = "sample\tdiagnosis\ttype\tnumber"
	open_file.write(title + "\n")
	for sample in sorted(gram_p.keys()):
		my_type = "Gram+"
		mydia = "NA"
		if sample in samples:
			mydia = samples[sample]
		else:
			continue
		mystr = sample + "\t" + mydia + "\t" + my_type + "\t" + str(gram_p[sample])
		open_file.write(mystr + "\n")
	# foreach sample

	for sample in sorted(gram_n.keys()):
		my_type = "Gram-"
		mydia = "NA"
		if sample in samples:
			mydia = samples[sample]
		else:
			continue
		mystr = sample + "\t" + mydia + "\t" + my_type + "\t" + str(gram_n[sample])
		open_file.write(mystr + "\n")
	# foreach sample
	open_file.close()

	outfile2 = re.sub(".tsv", ".detail.tsv", outfile)
	outfile2_1 = re.sub(".detail.tsv", ".all.member_detail.tsv", outfile)
	open_file2_1 = open(outfile2_1, "w")
	open_file2_1.write("familyID\tmember\ttype\n")

	"""

	open_file2 = open(outfile, "w")
	title = utilities.PROTEIN_FAMILY_ID + "\ttype\tdetail\tconsistency"
	open_file2.write(title + "\n")
	details = {}
	details_rep = {}
	cluster_id = {}
	pers = {}
	pers_cluster = {}
	ann_info = {}
	for myclust in cluster.keys():
		mytotal = len(cluster[myclust].keys())
		mysignal = 0
		clust_id = ""
		for myid in cluster[myclust].keys():
			clust_id = cluster[myclust][myid]
			if not clust_id in ann_info:
				ann_info[clust_id] = {}
			if myid in signals:
				mysignal = mysignal + 1
				ann_info[clust_id][myid] = "SignalP_signaling"
			else:
				ann_info[clust_id][myid] = "No"
		# foreach member
		myper = round(float(mysignal)/float(mytotal), 2)
		if mysignal != 0:
			cluster_id[clust_id] = ""
			if not myper in pers:
				pers[myper] = {}
			if not mytotal in pers[myper]:
				pers[myper][mytotal] = {}
			pers[myper][mytotal][clust_id] = ""
			pers_cluster[clust_id] = str(mytotal) + "\t" + str(mysignal)
			if myper >= float(cutoff):
				details[clust_id] = "SignalP_signaling\tSignalP_signaling\t" + str(myper)
			if myclust in signals:	# the centroid is annotated
				details_rep[clust_id] = "SignalP_signaling\tSignalP_signaling\t" + str(myper)
	# foreach peptide
	for myclust in sorted(cluster_id.keys()):
		if assign_flag == "centroid":  # assign annotation based on representative info
			if myclust in details_rep:
				open_file2.write(myclust + "\t" + details_rep[myclust] + "\n")
		if assign_flag == "consistency":  # assign annotation baed on consistency info
			if myclust in details:
				open_file2.write(myclust + "\t" + details[myclust] + "\n")
	# foreach cluster
	open_file2.close()
	#for myclust in sorted(ann_info.keys()):
	#	for myid in sorted(ann_info[myclust].keys()):
	#		open_file2_1.write(myclust + "\t" + myid + "\t" + ann_info[myclust][myid] + "\n")
	#open_file2_1.close()

	outfile2 = re.sub(".detail.tsv", ".all.spectrum.tsv", outfile)
	open_file2 = open(outfile2, "w")
	title = "percentage\tmember_num\tnumber"
	open_file2.write(title + "\n")
	for myper in sorted(pers.keys(), key=float):
		for mem_num in sorted(pers[myper], key=int):
			mynum = len(pers[myper][mem_num].keys())
			open_file2.write(str(myper) + "\t" + str(mem_num) + "\t" + str(mynum) + "\n")
	# foreach percentage
	open_file2.close()

	"""	
	outfile2 = re.sub(".tsv", ".all.cluster_info.tsv", outfile)
	open_file2 = open(outfile2, "w")
	title = "familyID\tmember_num\tmotif_num"
	open_file2.write(title + "\n")
	for myid in sorted(pers_cluster.keys()):
		open_file2.write(myid + "\t" + pers_cluster[myid] + "\n")
	# foreach family
	open_file2.close()
	"""

# output_info


#==============================================================
###########  Main processing ############
#==============================================================
def main():

	### get arguments ###
	values = get_args ()
	myfamily = config.protein_family
	if values.cluster:
		myfamily = values.cluster

	config.logger.info ("### Start interproscan_signalp_protein_family step ####")

	config.logger.info ("Get info ......starting")
	cluster, cluster_mem = collect_cluster_info (myfamily)
	config.logger.info ("Get info ......done")

	### collect annotation info and do stat ###
	config.logger.info ("Get signaling info ......starting")
	gram_p, gram_n, signals, signals_p, signals_n = collect_signaling_info (cluster_mem, values.extension, values.path, values.output)
	config.logger.info ("Get signaling info ......done")

	### Output sample info
	config.logger.info ("Output signaling summary info ......starting")
	output_info (config.tshld_consistency, cluster, gram_p, gram_n, signals, signals_p, signals_n, values.method, values.output)
	config.logger.info ("Output signaling summary info ......done")

	config.logger.info ("### Finish interproscan_signalp_protein_family step ####")

# end: main

if __name__ == '__main__':
	main()
