#! /usr/bin/env python 
###################################
#    Davi Ortega 1/29/2014 
###################################
import pymongo
import sys
import numpy

if '-h' in sys.argv:
	print 'This will take forever and it will require some reasonable disc space. Carefull now'
	sys.exit()

#MONGO
try:
	client = pymongo.MongoClient('localhost',27017)
except Connection:
	print "You must open a tunnel with ares.bio.utk.edu: ssh -L 27017:are.bio.utk.edu:27017 ares.bio.utk.edu"
	sys.exit()
mist = client.mist22
#END MONGO

output = ''
no_sequence = ''

i = 0

for aseq in mist.aseqs.find({},{"s":1}):
	if numpy.mod(i,5000) == 0:
		print i
	try:
		seq = str(aseq["s"]) + '\n'
		go = 1
	except KeyError:
		go = 0
		pass

	if go == 1:
		g = mist.genes.find_one({"p.aid":aseq["_id"]}, {"lo":1, "gid":1, "p.ac":1})
		if "lo" not in g.keys():
			g["lo"] = ''
		try:
			tag = ">" + str(g['gid']) + "-" + str(g['lo']) + "-" + str(g['p']['ac']) + '\n'
		except KeyError:
			print g
			tag = None
		if tag:
			output += tag + seq
		else:
			no_sequence += str(g) + '\n'
	i += 1

datafile = open('mist.fa','w')
datafile.write(output)
datafile.close()

datafile = open('mist.tags_noseq','w')
datafile.write(no_sequence)
datafile.close()


