#!/usr/bin/env python

from __future__ import division, print_function, unicode_literals

__doc__ = """write """
__version__ = '1.0.0'

import os, sys
from filecache import filecache, WEEK
import logging

import IPython
import sqlalchemy.exc
import sqlsoup

from locus.core.exceptions import LocusNCBIError
import locus.ncbi.gene
import locus.ncbi.refseq
import locus.ncbi.helpers as lnh


def _strand_as_signed_int(plus_minus):
    if plus_minus == 'plus':  return  1
    if plus_minus == 'minus': return -1
    raise RuntimeError('strand "'+plus_minus+'" not understood')

def load_transcript(tx_db,nm):
    @filecache(WEEK)
    def _refseq(nm):
        return lnh.efetch_nuccore_by_ac(nm)

    t = locus.ncbi.refseq.RefSeq( _refseq(nm) )
    t_exons = t.exons
    t_ex_names = t.exon_names
    assert len(t_exons) == len(t_ex_names), nm+": exon <s,e> list and exon name list have different numbers of elements"

    cds_start_i,cds_end_i = t.cds_start_end_i
    tx_db.transcript.insert( ac = nm, 
                             gene = t.gene[0],
                             cds_start_i = cds_start_i,
                             cds_end_i = cds_end_i,
                             seq = t.seq )
    tx_db.commit()
    for i,sen in enumerate(zip(t_exons,t_ex_names)):
        tx_db.transcript_exon.insert(ac = nm,  name = sen[1], ord = i+1,
                                     start_i = sen[0][0], end_i = sen[0][1])
    tx_db.commit()

    return


if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)

    # database schema defined in db.sql
    # 'postgresql:///' == local socket connection
    tx_db = sqlsoup.SQLSoup('postgresql:///reece')

    for nm in sys.argv[1:]:
        try:
            load_transcript(tx_db,nm)
        except (AssertionError,LocusNCBIError,sqlalchemy.exc.SQLAlchemyError) as e:
            tx_db.rollback()
            logging.warn('transcript %s: %s' % (nm,str(e)))

## <LICENSE>
## Copyright 2014 UTA Contributors (https://bitbucket.org/invitae/uta)
## 
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
## 
##     http://www.apache.org/licenses/LICENSE-2.0
## 
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
## </LICENSE>
