#! /usr/bin/env python
#
# Copyright INRA-URGI 2009-2012
# 
# 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.
#
import os
from optparse import OptionParser, OptionGroup
from commons.core.parsing.ParserChooser import ParserChooser
from commons.core.writer.Gff3Writer import Gff3Writer
from SMART.Java.Python.structure.Transcript import Transcript
from SMART.Java.Python.ncList.NCListFilePickle import NCListFileUnpickle
from SMART.Java.Python.ncList.FileSorter import FileSorter
from SMART.Java.Python.misc.Progress import Progress
from SMART.Java.Python.misc import Utils


class GetUpDownStream(object):

    def __init__(self, verbosity = 0):
        self.verbosity         = verbosity
        self.inputReader       = None
        self.outputWriter      = None
        self.nbRead            = 0
        self.nbWritten         = 0
        self.nbMerges          = 0
        self.splittedFileNames = {}

    def __del__(self):
        for fileName in self.splittedFileNames.values():
            os.remove(fileName)
            
    def setInputFile(self, fileName, format):
        parserChooser = ParserChooser(self.verbosity)
        parserChooser.findFormat(format, "transcript")
        self.parser = parserChooser.getParser(fileName)
        self.sortedFileName = "%s_sorted.pkl" % (os.path.splitext(fileName)[0])

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

    def setDistances(self, up, down):
        self.upDistance   = up
        self.downDistance = down

    def _sortFile(self):
        fs = FileSorter(self.parser, self.verbosity-4)
        fs.perChromosome(True)
        fs.setOutputFileName(self.sortedFileName)
        fs.sort()
        self.splittedFileNames       = fs.getOutputFileNames()
        self.nbElementsPerChromosome = fs.getNbElementsPerChromosome()
        self.nbRead                  = fs.getNbElements()

    def _write(self, start, end, reference, after):
        if start > end:
            return
        transcript = Transcript()
        transcript.setChromosome(reference.getChromosome())
        transcript.setStart(start)
        transcript.setEnd(end)
        transcript.setDirection("+")
        transcript.setName("%s_%s" % ("up" if Utils.xor(reference.getDirection() == 1, after) else "down", reference.getName()))
        self.outputWriter.addTranscript(transcript)
        
    def _getFlanking(self, chromosome):
        progress    = Progress(self.nbElementsPerChromosome[chromosome], "Analyzing chromosome %s" % (chromosome), self.verbosity)
        parser      = NCListFileUnpickle(self.splittedFileNames[chromosome], self.verbosity)
        previous    = None
        for transcript in parser.getIterator():
            progress.inc()
            transcript.removeExons()
            if previous == None:
                distance = self.upDistance if transcript.getDirection() == 1 else self.downDistance
                start    = max(1, transcript.getStart() - distance)
                self._write(start, transcript.getStart()-1, transcript, False)
                previous = transcript
                continue
            if previous.include(transcript):
                continue
            if transcript.overlapWith(previous):
                previous = transcript
                continue
            distancePrevious = self.downDistance if previous.getDirection()   == 1 else self.upDistance
            distanceCurrent  = self.upDistance   if transcript.getDirection() == 1 else self.downDistance
            distance = transcript.getDistance(previous)
            if distancePrevious + distanceCurrent == 0:
                previous = transcript
                continue
            if distance >= distancePrevious + distanceCurrent:
                endPrevious  = previous.getEnd() + distancePrevious
                startCurrent = transcript.getStart() - distanceCurrent
            else:
                middle       = previous.getEnd() + int((distance-1) * float(distancePrevious) / (distancePrevious + distanceCurrent))
                endPrevious  = middle
                startCurrent = middle+1
            self._write(previous.getEnd() + 1, endPrevious, previous, True)
            self._write(startCurrent, transcript.getStart() - 1, transcript, False)
            previous = transcript
        distance = self.downDistance if previous.getDirection() == 1 else self.upDistance
        self._write(previous.getEnd() + 1, previous.getEnd() + distance, previous, True)
        progress.done()

    def run(self):
        self._sortFile()
        for chromosome in sorted(self.nbElementsPerChromosome.keys()):
            self._getFlanking(chromosome)
        self.outputWriter.close()

if __name__ == "__main__":
    
    # parse command line
    description = "Get Up and Down Stream v1.0.0: Get the flanking regions of an annotation. [Category: Data Modification]"

    parser = OptionParser(description = description)
    parser.add_option("-i", "--input",     dest="inputFileName",  action="store",                     type="string", help="input file [compulsory] [format: file in mapping format given by -f]")
    parser.add_option("-f", "--format",    dest="format",         action="store",                     type="string", help="format of the file [compulsory] [format: mapping file format]")
    parser.add_option("-o", "--output",    dest="outputFileName", action="store",                     type="string", help="output file [compulsory] [format: output file in GFF3 format]")
    parser.add_option("-u", "--up",        dest="up",             action="store",      default=0,     type="int",    help="the upstream distance  [format: int]")
    parser.add_option("-d", "--down",      dest="down",           action="store",      default=0,     type="int",    help="the downstream distance  [format: int]")
    parser.add_option("-v", "--verbosity", dest="verbosity",      action="store",      default=1,     type="int",    help="trace level [default: 1] [format: int]")
    (options, args) = parser.parse_args()

    guds = GetUpDownStream(options.verbosity)
    guds.setInputFile(options.inputFileName, options.format)
    guds.setOutputFile(options.outputFileName)
    guds.setDistances(options.up, options.down)
    guds.run()
