import csv


def loadAnnotationsFromFile(filename, sample_name, csv_separator):
	""" loadAnnotationsFromFile(): 	Loads ORF annotations from a specified file and returns the relevant fields for each ORF

									Parameters:
									- filename: name of the file to load annotations from
									- sample_name: name of the sample these annotations are for (to properly format the IDs)
									- csv_separator: column separator used in given file

									Returns: a tuple - (name of sample, dict of tuples of annotation data indexed by ORF ID) """

	anno_data=(sample_name, {})

	try:
		# Load the specified annotations file
		with open(filename, 'r') as anno_file:
			anno_reader = csv.reader(anno_file, delimiter=csv_separator)

			# Process each row in the annotations file and store the relevant data
			for row in anno_reader:
				if row[0] == '#query': # Skip the header row
					continue

				 # Generate the proper corresponding ORF ID - if the sample name is part of the ID, remove it.
				if sample_name in row[0]:
					anno_query = 'O_' + row[0].replace(sample_name,'')[1:]
				else:
					anno_query = 'O_' + row[0]

				# Only take the first annotation result from each ORF
				if anno_query in anno_data[1]:
					continue

				anno_hit = row[9].split('[')[0] # Grab only the name of the gene as the 'hit'
				anno_q_length = row[2] 	# 'q_length' column
				anno_bitscore = row[3] 	# 'bitscore' column
				anno_bsr = row[4] 		# 'bsr' column
				anno_expect = row[5]	# 'expect' column
				anno_identity = row[7] 	# 'identity' column
				anno_ec = row[8] 		# 'ec' column

				# Store the loaded data in the dict in anno_data, which is keyed by the ORF ID
				anno_data[1][anno_query] = (anno_hit, anno_q_length, anno_bitscore, anno_bsr, anno_expect, anno_identity, anno_ec)

	# If an error was encountered loading and processing the annotation file, exit and print the error
	except Exception as e:
		print("Error reading annotation file - exiting.")
		print("Exception: " + str(e))
		quit()


	return anno_data