#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @package parse_blast.py
# @author Lea Picard

import sys, os, subprocess
from Bio import Entrez, SeqIO
from collections import defaultdict

def dict2fasta(dico):
	"""
	Function that takes a dictionary with key are ID and value Seq, and returns a fasta string.
	:param dico: a python dictionary
	:type dico: dict()
	:rtype: fasta str()
	:return: string with format fasta
	Example:
		>>> dico = {"Seq1":"ATGCTGCAGTAG","Seq2":"ATGCCGATCGATG","Seq3":"ATGCTCAGTCAGTAG"}
		>>> dict2fasta(dico)
		>Seq1
		ATGCTGCAGTAG
		>Seq2
		ATGCCGATCGATG
		>Seq3
		ATGCTCAGTCAGTAG
	"""

	txtoutput = ""
	for key, value in dico.items():
		txtoutput += ">%s\n%s\n" % (str(key),str(value))
	return txtoutput


blastRes = "/panhome/lpicard/localdata/21genes_blast_20170709/results_test_outfmt3.tsv"

dGene2SpAcc = defaultdict(list) # dict of dict d[gene][sp] = acc 
dSp2Acc = {} # dict keys = taxID, values = accession for this tax
dGene2Out = {} # dict keys = gene, values = outfile 
outDir = "/".join(blastRes.split("/")[0:-1])
geneName = ""
print(outDir)

# split blast results by gene
with open(blastRes, "r") as blast:
	separator = blast.readline().strip()
	print(separator)
	#listBlastRes = blast.read().strip().split('# BLASTN 2.2.31+')

"""
# for each gene result in blast results
for geneRes in listBlastRes:
	if geneRes == "":
		next
	else:
		for hit in geneRes.split("\n"):
			# get gene name from results header, create output file name and initialize dGene2TaxAcc for each gene
			if hit.startswith("# Query"):
				geneName = hit.split(" ")[2].split("|")[1]
				dGene2Out[geneName] = outDir+"/"+geneName+".fasta"
				#dGene2TaxAcc[geneName] = {}
			# skip other lines in the header
			elif hit.startswith("#") and not hit.startswith("# Query") or hit == "":
				next
			# parse hits (get gene accession ID and taxID)
			else:
				cols = hit.split("\t")
				geneAcc = cols[1].split("|")[3]
				taxID = cols[2]

				dGene2TaxAcc[geneName].append(geneAcc)
	
for gene in dGene2TaxAcc.keys():
	outFile = outDir+"/"+gene+"_Acc.txt"
	print(outFile)
	lAcc = "\n".join(dGene2TaxAcc[gene])
	with open(outFile, "w") as out:
		out.write(lAcc)
"""
