#! /usr/bin/env python
#
# Copyright INRA-URGI 2009-2010
# 
# This software is governed by the CeCILL license under French law and
# abiding by the rules of distribution of free software. You can use,
# modify and/ or redistribute the software under the terms of the CeCILL
# license as circulated by CEA, CNRS and INRIA at the following URL
# "http://www.cecill.info".
# 
# As a counterpart to the access to the source code and rights to copy,
# modify and redistribute granted by the license, users are provided only
# with a limited warranty and the software's author, the holder of the
# economic rights, and the successive licensors have only limited
# liability.
# 
# In this respect, the user's attention is drawn to the risks associated
# with loading, using, modifying and/or developing or reproducing the
# software by the user in light of its specific status of free software,
# that may mean that it is complicated to manipulate, and that also
# therefore means that it is reserved for developers and experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to load and test the software's suitability as regards their
# requirements in conditions enabling the security of their systems and/or
# data to be ensured and, more generally, to use and operate it in the
# same conditions as regards security.
# 
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL license and that you accept its terms.
#
"""
Clean a GFF file (as given by NCBI or TAIR) and outputs a GFF3 file.
"""

from SMART.Java.Python.cleaning.TranscriptListCleaner import TranscriptListCleaner
from SMART.Java.Python.misc.Progress import Progress
from SMART.Java.Python.misc.UnlimitedProgress import UnlimitedProgress

count = {}

class ParsedLine(object):
	def __init__(self, line, cpt):
		self.line = line
		self.cpt  = cpt
		self.parse()

	def parse(self):
		self.line = self.line.strip()
		self.splittedLine = self.line.split(None, 8)
		if len(self.splittedLine) < 9:
			raise Exception("Line '%s' has less than 9 fields.  Exiting..." % (self.line))
		self.type = self.splittedLine[2]
		self.parseOptions()
		self.getId()
		self.getParents()

	def parseOptions(self):
		self.parsedOptions = {}
		for option in self.splittedLine[8].split(";"):
			option = option.strip()
			if option == "": continue
			posSpace = option.find(" ")
			posEqual = option.find("=")
			if posEqual != -1 and (posEqual < posSpace or posSpace == -1):
				key, value = option.split("=", 1)
			elif posSpace != -1:
				key, value = option.split(None, 1)
			else:
				key   = "ID"
				value = option
			self.parsedOptions[key.strip()] = value.strip(" \"")

	def getId(self):
		for key in self.parsedOptions:
			if key.lower() == "id":
				self.id = self.parsedOptions[key]
				return
		if "Parent" in self.parsedOptions:
			parent = self.parsedOptions["Parent"].split(",")[0]
			if parent not in count:
				count[parent] = {}
			if self.type not in count[parent]:
				count[parent][self.type] = 0
			count[parent][self.type] += 1
			self.id = "%s-%s-%d" % (parent, self.type, count[parent][self.type])
		else:
			self.id = "smart%d" % (self.cpt)
		self.parsedOptions["ID"] = self.id

	def getParents(self):
		for key in self.parsedOptions:
			if key.lower() in ("parent", "derives_from"):
				self.parents = self.parsedOptions[key].split(",")
				return
		self.parents = None

	def removeParent(self):
		for key in self.parsedOptions.keys():
			if key.lower() in ("parent", "derives_from"):
				del self.parsedOptions[key]

	def export(self):
		self.splittedLine[8] = ";".join(["%s=%s" % (key, value) for key, value in self.parsedOptions.iteritems()])
		return "%s\n" % ("\t".join(self.splittedLine))


class GffCleaner(TranscriptListCleaner):

	def __init__(self, verbosity = 1):
		super(GffCleaner, self).__init__(verbosity)
		self.lines		 = {}
		self.acceptedTypes = ["mRNA", "transcript", "exon"]
		self.parents	   = []
		self.children	  = {}

	def getFileFormats():
		return ["gff", "gff2", "gff3"]
	getFileFormats = staticmethod(getFileFormats)

	def setAcceptedTypes(self, types):
		self.acceptedTypes = types

	def parse(self):
		progress = UnlimitedProgress(100000, "Reading input file", self.verbosity)
		for cpt, line in enumerate(self.inputHandle):
			if not line or line[0] == "#": continue
			if line[0] == ">": break
			parsedLine = ParsedLine(line, cpt)
			if self.acceptedTypes == None or parsedLine.type in self.acceptedTypes:
				self.lines[parsedLine.id] = parsedLine
			progress.inc()
		progress.done()

	def sort(self):
		progress = Progress(len(self.lines.keys()), "Sorting file", self.verbosity)
		for line in self.lines.values():
			parentFound = False
			if line.parents:
				for parent in line.parents:
					if parent in self.lines:
						parentFound = True
						if parent in self.children:
							self.children[parent].append(line)
						else:
							self.children[parent] = [line]
			if not parentFound:
				line.removeParent()
				self.parents.append(line)
			progress.inc()
		progress.done()

	def write(self):
		progress = Progress(len(self.parents), "Writing output file", self.verbosity)
		for line in self.parents:
			self.writeLine(line)
			progress.inc()
		progress.done()

	def writeLine(self, line):
		self.outputHandle.write(line.export())
		if line.id in self.children:
			for child in self.children[line.id]:
				self.writeLine(child)

	def _clean(self):
		self.parse()
		self.sort()
		self.write()
