#
# 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.
#
import random
import sys
from SMART.Java.Python.structure.TranscriptList import TranscriptList
from SMART.Java.Python.mySql.MySqlExonTable import MySqlExonTable
from SMART.Java.Python.mySql.MySqlTable import MySqlTable
from SMART.Java.Python.structure.Transcript import Transcript
from SMART.Java.Python.misc.Progress import Progress

class MySqlTranscriptTable(MySqlTable):
    """A table of transcripts in a mySQL database"""

    def __init__(self, connection, name = None, chromosome = None, verbosity = 0):
        if chromosome == None:
            chromosome = ""
        else:
            chromosome = "_%s" % chromosome
        if name == None:
            name = "TmpTable_%d" % (random.randint(0, 100000))
        name = "%s%s" % (name, chromosome)
        super(MySqlTranscriptTable, self).__init__(connection, "%s_transcripts" % name, verbosity)


    def createTranscriptTable(self):
        self.create(Transcript.getSqlVariables(), Transcript.getSqlTypes(), Transcript.getSqlSizes())


    def rename(self, name):
        super(MySqlTranscriptTable, self).rename("%s_transcripts" % name)


    def remove(self):
        super(MySqlTranscriptTable, self).remove()
        
        
    def clear(self):
        super(MySqlTranscriptTable, self).clear()

        
    def copy(self, transcriptTable):
        self.remove()
        super(MySqlTranscriptTable, self).copy(transcriptTable)


    def add(self, transcriptTable):
        super(MySqlTranscriptTable, self).add(transcriptTable)


    def addTranscript(self, transcript):
        id = self.addLine(transcript.getSqlValues())
        transcript.id = id
            
            
    def addTranscriptList(self, transcriptList):
        progress = Progress(transcriptList.getNbTranscript(), "Storing list to %s" % (self.name), self.verbosity)
        for transcript in transcriptList.getIterator():
            self.addTranscript(transcript)
            progress.inc()
        progress.done()

            
    def removeTranscript(self, transcript):
        self.removeFromId(transcript.id)
            
            
    def retrieveTranscriptFromId(self, id):
        transcript = Transcript()
        transcript.setSqlValues(self.retrieveFromId(id))
        return transcript
    
    
    def retrieveBulkTranscriptFromId(self, ids):
        if not ids:
            return []
        transcripts = self.retrieveBulkFromId(ids)
        idsToTranscripts = {}
        for values in transcripts:
            transcript = Transcript()
            transcript.setSqlValues(values)
            idsToTranscripts[values[0]] = transcript
        return idsToTranscripts.values()
    
    
    def selectTranscripts(self, command, simple = False):
        MAXSIZE = 100000
        found   = True
        cpt     = 0
        while found:
            found = False
            if simple:
                thisCommand = command
            else:
                thisCommand = "%s LIMIT %d OFFSET %d" % (command, MAXSIZE, MAXSIZE * cpt)
            query = self.mySqlConnection.executeQuery(thisCommand)
            for line in query.getIterator():
                found      = True
                id         = int(line[0])
                transcript = Transcript()
                transcript.setSqlValues(line)
                yield (id, transcript)
            cpt += 1
            if simple:
                return

    
    def getIterator(self):
        for id, transcript in self.selectTranscripts("SELECT * FROM '%s'" % (self.name)):
            yield transcript


    def retrieveTranscriptList(self):
        transcriptList = TranscriptList()
        for transcriptLine in self.getLines():
            transcript = Transcript()
            transcript.setSqlValues(transcriptLine)
            transcriptList.addTranscript(transcript)
        return transcriptList
            

    def setDefaultTagValue(self, name, value):
        super(MySqlTranscriptTable, self).setDefaultTagValue(Transcript.getSqlVariables().index("tags")+1, name, value)