#! /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.
#
"""Restrict a transcript list with some parameters (regions)"""

from optparse import OptionParser
from SMART.Java.Python.structure.Transcript import Transcript
from SMART.Java.Python.structure.TranscriptContainer import TranscriptContainer
from SMART.Java.Python.structure.TranscriptListsComparator import TranscriptListsComparator
from commons.core.writer.Gff3Writer import Gff3Writer
from commons.core.parsing.FastaParser import FastaParser
from SMART.Java.Python.misc.Progress import Progress

class DifferenceGetter(object):

    def __init__(self, verbosity):
        self.verbosity        = verbosity
        self.annotationParser = None
        self.referenceParser  = None
        self.sequenceParser   = None
        self.transcriptCount  = 1
        self.split            = False

    def createTranscript(self, chromosome, start, end):
        transcript = Transcript()
        transcript.setChromosome(chromosome)
        transcript.setDirection("+")
        transcript.setStart(start)
        transcript.setEnd(end)
        transcript.setName("region_%d" % self.transcriptCount)
        transcript.setTagValue("ID", "region_%d" % self.transcriptCount)
        self.transcriptCount += 1
        return transcript

    def setSplit(self, split):
        self.split = split

    def setAnnotationFile(self, fileName, format):
        if fileName != None:
            self.annotationParser = TranscriptContainer(fileName, format, self.verbosity)

    def setReferenceFile(self, fileName, format):
        if fileName != None:
            self.referenceParser = TranscriptContainer(fileName, format, self.verbosity)

    def setSequenceFile(self, fileName):
        if fileName != None:
            self.sequenceParser = FastaParser(fileName, self.verbosity)

    def setOutputFile(self, fileName):
        self.writer = Gff3Writer(fileName, self.verbosity)

    def initialize(self):
        self.presence = {}
        for chromosome in self.sequenceParser.getRegions():
            self.presence[chromosome] = [[1, self.sequenceParser.getSizeOfRegion(chromosome)]]

    def readTranscripts(self):
        nbTranscripts = self.annotationParser.getNbTranscripts()
        progress      = Progress(nbTranscripts, "Parsing annotation file" , self.verbosity)
        for transcript in self.annotationParser.getIterator():
            chromosome   = transcript.getChromosome()
            toBeDeleted  = []
            toBeAppended = []
            for i, element in enumerate(self.presence[chromosome]):
                start, end = element
                if start <= transcript.getEnd() and transcript.getStart() <= end:
                    toBeDeleted.append(i)
                    if start < transcript.getStart():
                        toBeAppended.append([start, transcript.getStart() - 1])
                    if end > transcript.getEnd():
                        toBeAppended.append([transcript.getEnd() + 1, end])
            for i in reversed(toBeDeleted):
                del self.presence[chromosome][i]
            self.presence[chromosome].extend(toBeAppended)
            progress.inc()
        progress.done()

    def writeOutput(self):
        for chromosome in self.presence:
            for element in self.presence[chromosome]:
                start, end = element
                self.writer.addTranscript(self.createTranscript(chromosome, start, end))
        self.writer.write()

    def compareToSequence(self):
        self.initialize()
        self.readTranscripts()
        self.writeOutput()

    def compareToAnnotation(self):
        transcriptListComparator = TranscriptListsComparator(None, self.verbosity)
        transcriptListComparator.setSplitDifference(self.split)
        transcriptListComparator.setInputTranscriptContainer(transcriptListComparator.QUERY, self.annotationParser)
        transcriptListComparator.setInputTranscriptContainer(transcriptListComparator.REFERENCE, self.referenceParser)
        transcriptListComparator.setOutputWriter(self.writer)
        transcriptListComparator.getDifferenceTranscriptList()

    def run(self):
        if self.referenceParser != None:
            self.compareToAnnotation()
        else:
            self.compareToSequence()


if __name__ == "__main__":
    
    # parse command line
    description = "Get Difference v1.0.1: Get all the regions of the genome, except the one given or get all the elements from the first set which does not ovelap with the second set (at the nucleotide level). [Category: Data Comparison]"

    parser = OptionParser(description = description)
    parser.add_option("-i", "--input1",    dest="inputFileName1",   action="store",                     type="string", help="input file [compulsory] [format: file in transcript format given by -f]")
    parser.add_option("-f", "--format1",   dest="format1",          action="store",                     type="string", help="format [compulsory] [format: transcript file format]")
    parser.add_option("-j", "--input2",    dest="inputFileName2",   action="store",      default=None,  type="string", help="reference file [format: file in transcript format given by -g]")
    parser.add_option("-g", "--format2",   dest="format2",          action="store",      default=None,  type="string", help="format of the reference file [format: transcript file format]")
    parser.add_option("-s", "--sequence",  dest="sequenceFileName", action="store",      default=None,  type="string", help="sequence file [format: file in FASTA format]")
    parser.add_option("-p", "--split",     dest="split",            action="store_true", default=False,                help="when comparing to a set of genomic coordinates, do not join [format: boolean] [default: False")
    parser.add_option("-o", "--output",    dest="outputFileName",   action="store",                     type="string", help="output file [format: output file in GFF3 format]")
    parser.add_option("-v", "--verbosity", dest="verbosity",        action="store",      default=1,     type="int",    help="trace level [format: int]")
    (options, args) = parser.parse_args()

    getter = DifferenceGetter(options.verbosity)
    getter.setSplit(options.split)
    getter.setAnnotationFile(options.inputFileName1, options.format1)
    getter.setSequenceFile(options.sequenceFileName)
    getter.setReferenceFile(options.inputFileName2, options.format2)
    getter.setOutputFile(options.outputFileName)
    getter.run()
