import sqlite3
import itertools
import operator


def get_annotations(database, feat_type, pass_list=None):
	"""
		Extracts annotations from the gene/transcript/exon annotation table of
		the database (depending on choice of feat_type).

		Returns:
			annotation_dict: dictionary data structure in which the keys are
							 gene/transcript/exon TALON IDs (depending on
							 choice of feat_type) and the value is a list of
							 annotation tuples.
	"""
	# fetch the annotations
	conn = sqlite3.connect(database)
	cursor = conn.cursor()

	table_name = feat_type + "_annotations"

	if pass_list == None:
		query = "SELECT * FROM " + table_name
	else:
		pass_list_string = "(" + ','.join([str(x) for x in pass_list]) + ")"
		query = "SELECT * FROM " + table_name + " WHERE ID IN " + pass_list_string

	cursor.execute(query)
	annotation_tuples = cursor.fetchall()

	# sort based on ID
	sorted_annotations = sorted(annotation_tuples, key=lambda x: x[0])

	# group by ID and store in a dictionary
	ID_groups = {}
	for key,group in itertools.groupby(sorted_annotations,operator.itemgetter(0)):
		ID_groups[key] = list(group)

	return ID_groups