#! /usr/bin/env python 
###################################
#    Davi Ortega 7/23/2014 
###################################
import bitk
import sys
if '-h' in sys.argv:
	print 'Input list of smart tags or Seqdepot qseqs output fasta file'
	sys.exit()

mist22 = bitk.get_mist22_client()
seqdepot = bitk.get_seqdepot_client()
output = ''
taglist = []
aclist = []

error = []

with open(sys.argv[1], 'r') as f:
	for line in f:
		taglist.append(line.replace('\n',''))
                try:
                    aclist.append(line.replace('\n','').split('-')[2])
                except 

cards = mist22.genes.find({ 'p.ac' : { '$in' : aclist }})
ac2aseq = {}
for card in cards:
	print card
	ac2aseq[card['p']['ac']] = card['p']['aid']

cards = seqdepot.aseqs.find({'_id' :  { '$in' : ac2aseq.values() }})
aseq2seq = {}
for card in cards:
	aseq2seq[card['_id']] = card['s']

for tag in taglist:
	try:
		output += '>' + tag + '\n' + aseq2seq[ac2aseq[tag.split('-')[2]]] + '\n'
	except KeyError:
		error.append(tag)		

with open(sys.argv[1] + '.fa', 'w') as f:
	f.write(output)

if len(error) != 0:
	with open(sys.argv[1] + '.error', 'w') as f:
		f.write(str(error))



