# Copyright 2007-2009 by Peter Cock.  All rights reserved.
#
# This code is part of the Biopython distribution and governed by its
# license.  Please see the LICENSE file that should have been included
# as part of this package..

"""Bio.SeqIO support for the "genbank" and "embl" file formats.

You are expected to use this module via the Bio.SeqIO functions.
Note that internally this module calls Bio.GenBank to do the actual
parsing of both GenBank and EMBL files.

See also:

International Nucleotide Sequence Database Collaboration
http://www.insdc.org/
 
GenBank
http://www.ncbi.nlm.nih.gov/Genbank/

EMBL Nucleotide Sequence Database
http://www.ebi.ac.uk/embl/

DDBJ (DNA Data Bank of Japan)
http://www.ddbj.nig.ac.jp/
"""

from Bio.Seq import UnknownSeq
from Bio.GenBank.Scanner import GenBankScanner, EmblScanner
from Bio import Alphabet
from Interfaces import SequentialSequenceWriter
from Bio import SeqFeature

# NOTE
# ====
# The "brains" for parsing GenBank and EMBL files (and any
# other flat file variants from the INSDC in future) is in
# Bio.GenBank.Scanner (plus the _FeatureConsumer in Bio.GenBank)
# However, all the writing code is in this file.


def GenBankIterator(handle):
    """Breaks up a Genbank file into SeqRecord objects.

    Every section from the LOCUS line to the terminating // becomes
    a single SeqRecord with associated annotation and features.
    
    Note that for genomes or chromosomes, there is typically only
    one record."""
    #This calls a generator function:
    return GenBankScanner(debug=0).parse_records(handle)

def EmblIterator(handle):
    """Breaks up an EMBL file into SeqRecord objects.

    Every section from the LOCUS line to the terminating // becomes
    a single SeqRecord with associated annotation and features.
    
    Note that for genomes or chromosomes, there is typically only
    one record."""
    #This calls a generator function:
    return EmblScanner(debug=0).parse_records(handle)

def GenBankCdsFeatureIterator(handle, alphabet=Alphabet.generic_protein):
    """Breaks up a Genbank file into SeqRecord objects for each CDS feature.

    Every section from the LOCUS line to the terminating // can contain
    many CDS features.  These are returned as with the stated amino acid
    translation sequence (if given).
    """
    #This calls a generator function:
    return GenBankScanner(debug=0).parse_cds_features(handle, alphabet)
    
def EmblCdsFeatureIterator(handle, alphabet=Alphabet.generic_protein):
    """Breaks up a EMBL file into SeqRecord objects for each CDS feature.

    Every section from the LOCUS line to the terminating // can contain
    many CDS features.  These are returned as with the stated amino acid
    translation sequence (if given).
    """
    #This calls a generator function:
    return EmblScanner(debug=0).parse_cds_features(handle, alphabet)

def _insdc_feature_position_string(pos, offset=0):
    """Build a GenBank/EMBL position string (PRIVATE).

    Use offset=1 to add one to convert a start position from python counting.
    """
    if isinstance(pos, SeqFeature.ExactPosition):
        return "%i" % (pos.position+offset)
    elif isinstance(pos, SeqFeature.WithinPosition):
        return "(%i.%i)" % (pos.position + offset,
                            pos.position + pos.extension + offset)
    elif isinstance(pos, SeqFeature.BetweenPosition):
        return "(%i^%i)" % (pos.position + offset,
                            pos.position + pos.extension + offset)
    elif isinstance(pos, SeqFeature.BeforePosition):
        return "<%i" % (pos.position + offset)
    elif isinstance(pos, SeqFeature.AfterPosition):
        return ">%i" % (pos.position + offset)
    elif isinstance(pos, SeqFeature.OneOfPosition):
        return "one-of(%s)" \
               % ",".join([_insdc_feature_position_string(p,offset) \
                           for p in pos.position_choices])
    elif isinstance(pos, SeqFeature.AbstractPosition):
        raise NotImplementedError("Please report this as a bug in Biopython.")
    else:
        raise ValueError("Expected a SeqFeature position object.")


def _insdc_location_string_ignoring_strand_and_subfeatures(feature):
    if feature.ref:
        ref = "%s:" % feature.ref
    else:
        ref = ""
    assert not feature.ref_db
    if feature.location.start==feature.location.end \
    and isinstance(feature.location.end, SeqFeature.ExactPosition):
        #Special case, 12^13 gets mapped to location 12:12
        #(a zero length slice, meaning the point between two letters)
        return "%s%i^%i" % (ref, feature.location.end.position,
                            feature.location.end.position+1)
    else:
        #Typical case, e.g. 12..15 gets mapped to 11:15
        return ref \
               + _insdc_feature_position_string(feature.location.start, +1) \
               + ".." + \
               _insdc_feature_position_string(feature.location.end)

def _insdc_feature_location_string(feature):
    """Build a GenBank/EMBL location string from a SeqFeature (PRIVATE)."""
    # Have a choice of how to show joins on the reverse complement strand,
    # complement(join(1,10),(20,100)) vs join(complement(20,100),complement(1,10))
    # Notice that the order of the entries gets flipped!
    #
    # GenBank and EMBL would both use now complement(join(1,10),(20,100))
    # which is shorter at least.
    #
    # In the above situations, we expect the parent feature and the two children
    # to all be marked as strand==-1, and in the order 0:10 then 19:100.
    #
    # Also need to consider dual-strand examples like these from the Arabidopsis
    # thaliana chloroplast NC_000932: join(complement(69611..69724),139856..140650)
    # gene ArthCp047, GeneID:844801 or its CDS which is even better due to a splice:
    # join(complement(69611..69724),139856..140087,140625..140650)
    # protein NP_051038.1 GI:7525057
    #

    if not feature.sub_features:
        #Non-recursive.
        #assert feature.location_operator == "", \
        #       "%s has no subfeatures but location_operator %s" \
        #       % (repr(feature), feature.location_operator)
        location = _insdc_location_string_ignoring_strand_and_subfeatures(feature)
        if feature.strand == -1:
            location = "complement(%s)" % location
        return location
    # As noted above, treat reverse complement strand features carefully:
    if feature.strand == -1:
        for f in feature.sub_features:
            assert f.strand == -1
        return "complement(%s(%s))" \
               % (feature.location_operator,
                  ",".join(_insdc_location_string_ignoring_strand_and_subfeatures(f) \
                           for f in feature.sub_features))
    #if feature.strand == +1:
    #    for f in feature.sub_features:
    #        assert f.strand == +1
    #This covers typical forward strand features, and also an evil mixed strand:
    assert feature.location_operator != ""
    return  "%s(%s)" % (feature.location_operator,
                        ",".join([_insdc_feature_location_string(f) \
                                  for f in feature.sub_features]))


class GenBankWriter(SequentialSequenceWriter):
    HEADER_WIDTH = 12
    MAX_WIDTH = 80
    QUALIFIER_INDENT = 21
    
    def _write_single_line(self, tag, text):
        "Used in the the 'header' of each GenBank record."""
        assert len(tag) < self.HEADER_WIDTH
        assert len(text) < self.MAX_WIDTH - self.HEADER_WIDTH, \
               "Annotation %s too long for %s line" % (repr(text), tag)
        self.handle.write("%s%s\n" % (tag.ljust(self.HEADER_WIDTH),
                                      text.replace("\n"," ")))

    def _write_multi_line(self, tag, text):
        "Used in the the 'header' of each GenBank record."""
        #TODO - Do the line spliting while preserving white space?
        max_len = self.MAX_WIDTH - self.HEADER_WIDTH
        assert len(tag) < self.HEADER_WIDTH
        text = text.strip()
        if len(text) < max_len:
            self._write_single_line(tag, text)
            return

        words = text.split()
        assert max([len(w) for w in words]) < max_len, \
               "Your description cannot be broken into nice lines!"
        text = ""
        while words and len(text) + 1 + len(words[0]) < max_len:
            text += " " + words.pop(0)
            text = text.strip()
        assert len(text) < max_len
        self._write_single_line(tag, text)
        while words:
            text = ""
            while words and len(text) + 1 + len(words[0]) < max_len:
                text += " " + words.pop(0)
                text = text.strip()
            assert len(text) < max_len
            self._write_single_line("", text)
        assert not words

    def _write_multi_entries(self, tag, text_list):
        #used for DBLINK and any similar later line types.
        #If the list of strings is empty, nothing is written.
        for i, text in enumerate(text_list):
            if i==0:
                self._write_single_line(tag, text)
            else:
                self._write_single_line("", text)

    def _get_date(self, record) :
        default = "01-JAN-1980"
        try :
            date = record.annotations["date"]
        except KeyError :
            return default
        #Cope with a list of one string:
        if isinstance(date, list) and len(date)==1 :
            date = date[0]
        #TODO - allow a Python date object
        if not isinstance(date, str) or len(date) != 11 \
        or date[2] != "-" or date[6] != "-" \
        or not date[:2].isdigit() or not date[7:].isdigit() \
        or int(date[:2]) > 31 \
        or date[3:6] not in ["JAN","FEB","MAR","APR","MAY","JUN",
                             "JUL","AUG","SEP","OCT","NOV","DEC"] :
            #TODO - Check is a valid date (e.g. not 31 Feb)
            return default
        return date

    def _write_the_first_line(self, record):
        """Write the LOCUS line."""
        
        locus = record.name
        if not locus or locus == "<unknown name>":
            locus = record.id
        if not locus or locus == "<unknown id>":
            locus = self._get_annotation_str(record, "accession", just_first=True)
        if len(locus) > 16:
            raise ValueError("Locus identifier %s is too long" % repr(locus))

        if len(record) > 99999999999:
            #Currently GenBank only officially support up to 350000, but
            #the length field can take eleven digits
            raise ValueError("Sequence too long!")

        #Get the base alphabet (underneath any Gapped or StopCodon encoding)
        a = Alphabet._get_base_alphabet(record.seq.alphabet)
        if not isinstance(a, Alphabet.Alphabet):
            raise TypeError("Invalid alphabet")
        elif isinstance(a, Alphabet.ProteinAlphabet):
            units = "aa"
        elif isinstance(a, Alphabet.NucleotideAlphabet):
            units = "bp"
        else:
            #Must be something like NucleotideAlphabet or
            #just the generic Alphabet (default for fasta files)
            raise ValueError("Need a Nucleotide or Protein alphabet")

        #Get the molecule type
        #TODO - record this explicitly in the parser?
        if isinstance(a, Alphabet.ProteinAlphabet):
            mol_type = ""
        elif isinstance(a, Alphabet.DNAAlphabet):
            mol_type = "DNA"
        elif isinstance(a, Alphabet.RNAAlphabet):
            mol_type = "RNA"
        else:
            #Must be something like NucleotideAlphabet or
            #just the generic Alphabet (default for fasta files)
            raise ValueError("Need a DNA, RNA or Protein alphabet")