#!/usr/bin/env python
import sys,time,argparse

def main(args):
	sys.stdout.write("Start analysis: " + time.strftime("%a,%d %b %Y %H:%M:%S") + "\n")
	sys.stdout.flush()
	stat_ats(args.input,args.output,args.lr,args.cage)
	sys.stdout.write("Finish analysis: " + time.strftime("%a,%d %b %Y %H:%M:%S") + "\n")
	sys.stdout.flush()


def stat_ats(input_con_gpd,output_ats_gpd,min_lr,min_sr):
	for line in input_con_gpd:
		grp_ats_set = line.strip().split("\t")[-1]
		if grp_ats_set == "NA":
			print >>output_ats_gpd, "\t".join([line.strip(),"NA","NA"])
		else:
			grp_ats_pass_list = []
			for grp_ats in grp_ats_set.split(","):
				lr_c = int(grp_ats.split("_")[1])
				sr_c = int(grp_ats.split("_")[2])
				if lr_c >= min_lr and sr_c >= min_sr:
					grp_ats_pass_list.append(grp_ats)
			if grp_ats_pass_list == []:
				print >>output_ats_gpd, "\t".join([line.strip(),"-","0"])
			else:
				print >>output_ats_gpd, "\t".join([line.strip(),",".join(grp_ats_pass_list),str(len(grp_ats_pass_list))])

	input_con_gpd.close()
	output_ats_gpd.close()

def do_inputs():
	output_gpd_format = '''
1. gene id
2. isoform id
3. chromosome id
4. strand
5. TSS (+)
6. TTS (+)
7. number of support full-length long reads
8. number of support total long reads
9. exon count
10. exon start set
11. exon end set
12. For novel isoform, derived genic locus
13. For novel isoform, overlap percentage with derived genic locus
14. For novel singleton isoform, if it is located at the last exon of any known isoform. If yes, isoform ID otherwise '-'
15. For novel singleton isoform, the overlap percentage with the the last exon
16. For novel multi-exon isoform, number of splice sites are detected by anno and/or short reads; and the total number of splice sites
17. For novel multi-exon isoform, if the multi-exon isoform is the subset (based on splice junction combination) of known multi-exon isoform, isoform ID if yes otherwise '-'
18. For novel isoform, maximal length of polyA track in defined region
19. For novel isoform, maximal percentage of nucleotide A in defined region
20. Individual TSS information: TSS postion; number of supporting long reads; number of supporting CAGE position
21. Grouped TSS information: TSS postion; number of supporting long reads; number of supporting CAGE position
22. Grouped TSS information passing the criteria (supporting long reads and CAGE data): TSS postion; number of supporting long reads; number of supporting CAGE position
23. Number of TSSs passing the criteria (supporting long reads and CAGE data)'''

	parser = argparse.ArgumentParser(description="Function: generate final output file (gpd format)",formatter_class=argparse.ArgumentDefaultsHelpFormatter)
	parser.add_argument('-i','--input',type=argparse.FileType('r'),required=True,help="Input: constructed isoform with TSS information (GPD file) generated by 'py_isoseqats_generate_ats_output.py'")
	parser.add_argument('-l','--lr',type=int,default=1,help="Minimal number of supporting long reads")
	parser.add_argument('-c','--cage',type=int,default=0,help="Minimal level of supporting CAGE data ('0' means no CAGE data support)")
	parser.add_argument('-o','--output',type=argparse.FileType('w'),required=True,help="Output: constructed isoform with TSS information (GPD file)")
	args = parser.parse_args()
	return args

if __name__=="__main__":
	args = do_inputs()
	main(args)
