###########################################################################
#                                                                         #
# C O P Y R I G H T   N O T I C E                                         #
#  Copyright (c) 2003-10 by:                                              #
#    * California Institute of Technology                                 #
#                                                                         #
#    All Rights Reserved.                                                 #
#                                                                         #
# Permission is hereby granted, free of charge, to any person             #
# obtaining a copy of this software and associated documentation files    #
# (the "Software"), to deal in the Software without restriction,          #
# including without limitation the rights to use, copy, modify, merge,    #
# publish, distribute, sublicense, and/or sell copies of the Software,    #
# and to permit persons to whom the Software is furnished to do so,       #
# subject to the following conditions:                                    #
#                                                                         #
# The above copyright notice and this permission notice shall be          #
# included in all copies or substantial portions of the Software.         #
#                                                                         #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,         #
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF      #
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND                   #
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS     #
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN      #
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN       #
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE        #
# SOFTWARE.                                                               #
###########################################################################
#
# data for Caenorhaditis briggsae
import string
from cistematic.genomes import Genome
from os import environ

if environ.get("CISTEMATIC_ROOT"):
    cisRoot = environ.get("CISTEMATIC_ROOT") 
else:
    cisRoot = "/proj/genome"

geneDB = "%s/C_briggsae/cbriggsae.genedb" % cisRoot


def loadChromosome(db, chromPath, chromOutPath):
    seqArray = []
    seqLen = 0
    cbGenome = Genome("cbriggsae", dbFile=db)
    inFile = open(chromPath, "r")
    header = inFile.readline()
    while header != "":
        seqArray = []
        seqLen = 0
        chromID = header.strip()[1:]
        currentLine = inFile.readline()
        while currentLine != "" and currentLine[0] != ">":
            lineSeq = currentLine.strip()
            seqLen += len(lineSeq)
            seqArray.append(lineSeq)
            currentLine = inFile.readline()

        seq = string.join(seqArray, "")
        if seqLen < 900000:
            print "Added contig %s to database" % chromID
            cbGenome.addSequence(("cbriggsae", chromID), seq, "chromosome", str(seqLen))
            cbGenome.addChromosomeEntry(chromID, chromID, "db")
        else:
            outFileName = "%s%s.bin" % (chromOutPath, chromID)
            outFile = open("%s%s" % (cisRoot, outFileName), "w")
            outFile.write(seq)
            outFile.close()
            print "Added contig file %s to database" % outFileName
            cbGenome.addChromosomeEntry(chromID, outFileName, "file")

        header = currentLine

    inFile.close()


def loadGeneEntries(db, gffFile):
    cbGenome = Genome("cbriggsae", dbFile=db)
    geneFile = open(gffFile, "r")
    geneEntries = []
    geneAnnotations = []
    for line in geneFile:
        field = line[:-1].split("\t")
        if field[1] != "hybrid":
            continue

        if field[2] != "CDS":
            continue

        annot = field[8].split('"')
        gid = annot[1]
        geneID = ("cbriggsae", gid)
        annotation = string.join(annot[3:], "")
        gidVersion = 1
        try:
            gidVersion = giddots[2]
        except:
            pass

        start = int(field[3]) - 1
        stop = int(field[4]) - 1
        sense = field[6]
        chrom = field[0].strip()
        if sense == "+":
            sense = "F"
        else:
            sense = "R"

        if (geneID, chrom, start, stop, sense, "CDS", gidVersion) not in geneEntries:
            geneEntries.append((geneID, chrom, start, stop, sense, "CDS", gidVersion))
        if (geneID, annotation) not in geneAnnotations:
            geneAnnotations.append((geneID, annotation))

    print "Adding %d gene entries" % len(geneEntries)
    cbGenome.addGeneEntryBatch(geneEntries)

    print "Adding %d annotations" % len(geneAnnotations)
    cbGenome.addAnnotationBatch(geneAnnotations)


def loadFeatureEntries(db, gffFile):
    cbGenome = Genome("cbriggsae", dbFile=db)
    featureFile = open(gffFile, "r")
    featureEntries = []
    seenFeatures = {}
    featureTranslation = {"coding_exon": "CDS",
                          "three_prime_UTR": "3UTR", 
                          "five_prime_UTR": "5UTR"
    }

    for line in featureFile:
        field = line.split("\t")
        if field[1] != "hybrid":
            continue

        if field[2].strip() not in featureTranslation:
            continue

        featureType = featureTranslation[field[2].strip()]
        gidrev = field[8].split('"')
        gid = gidrev[1]
        geneID = ("cbriggsae", gid)
        gidVersion = 1
        start = int(field[3]) - 1
        stop = int(field[4]) - 1
        sense = field[6]
        chrom = field[0].strip()
        if sense == "+":
            sense = "F"
        else:
            sense = "R"

        if geneID not in seenFeatures:
            seenFeatures[geneID] = []
        if (gidVersion, start, stop, featureType) not in seenFeatures[geneID]:
            featureEntries.append((geneID, gidVersion, chrom, start, stop, sense, featureType))
            seenFeatures[geneID].append((gidVersion, start, stop, featureType))

    print "Adding %d feature entries" % len(featureEntries)
    cbGenome.addFeatureEntryBatch(featureEntries)


def createDBFile(db):
    cbGenome = Genome("cbriggsae", version="CB25",  dbFile=db)
    cbGenome.createGeneDB(db)


def createDBindices(db):
    cbGenome = Genome("cbriggsae", version="CB25", dbFile=db)
    cbGenome.createIndices()


def buildCbriggsaeDB(db=geneDB):
    gffPath = "%s/download/briggsae_25.WS132.gff" % cisRoot
    chromoPath = "%s/download/briggsae_25.fa" % cisRoot
    chromoOutPath = "/C_briggsae/"

    print "Creating database %s" % db
    createDBFile(db)

    print "Adding gene entries"
    loadGeneEntries(db, gffPath)

    print "Adding feature entries"
    loadFeatureEntries(db, gffPath)

    print "Loading genomic sequence" 
    loadChromosome(db, chromoPath, chromoOutPath)

    print "Creating Indices"
    createDBindices(db)

    print "Finished creating database %s" % db