
package uk.ac.sanger.pathogens.embl;

import java.io.IOException;
import java.util.Iterator;

import collections.CollectionEnumeration;

import uk.ac.sanger.pathogens.*;

public class BioJavaEntry extends ReadOnlyEntry implements Entry
{
    private FeatureTree                  featTree;
    private EntryInformation             information;
    private Sequence                     nativeSequence;

    private org.biojava.bio.seq.Sequence sequence;

    public BioJavaEntry(final             EntryInformation information,
			final org.biojava.bio.seq.Sequence sequence)
    {
	this.information = information;
	this.sequence    = sequence;

	featTree = new FeatureTree(new FeatureComparator());

	setNativeFeatures(sequence);
	setNativeSequence(sequence);
    }

    public String getHeaderText()
    {
	return null;
    }

    public EntryInformation getEntryInformation()
    {
	return information;
    }

    public String getName()
    {
	return sequence.getName();
    }

    public int getFeatureCount()
    {
	return featTree.size();
    }

    public Feature getFeatureAtIndex(final int index)
    {
	int thisIndex = 0;

	for (CollectionEnumeration fe = featTree.elements(); fe.hasMoreElements();)
	{
	    final Feature thisFeature = (Feature) fe.nextElement();
      
	    if (thisIndex == index)
		return thisFeature;

	    thisIndex++;
	}
	return null;
    }

    public int indexOf(final Feature feature)
    {
	int thisIndex = 0;

	for (CollectionEnumeration fe = featTree.elements(); fe.hasMoreElements();)
	{
	    final Feature thisFeature = (Feature) fe.nextElement();
      
	    if (thisFeature == feature)
		return thisIndex;

	    thisIndex++;
	}
	return -1;
    }

    public boolean contains(final Feature feature)
    {
	return featTree.includes(feature);
    }

    public FeatureEnumeration features()
    {
	return featTree.features();
    }

    public FeatureVector getFeaturesInRange(final Range range)
	throws OutOfRangeException
    {
	return featTree.getFeaturesInRange(range);
    }

    public FeatureVector getAllFeatures()
    {
	final FeatureVector allFeatures = new FeatureVector();

	for (CollectionEnumeration fe = featTree.elements(); fe.hasMoreElements();)
	{
	    final Feature thisFeature = (Feature) fe.nextElement();
      
	    allFeatures.add(thisFeature);
	}
	return allFeatures;
    }

    public Sequence getSequence()
    {
	return nativeSequence;
    }

    private void setNativeFeatures(final org.biojava.bio.seq.FeatureHolder holder)
    {
	for (Iterator fi = holder.features(); fi.hasNext();)
	{
	    org.biojava.bio.seq.Feature f = (org.biojava.bio.seq.Feature) fi.next();
	    featTree.add(new BioJavaFeature(f));
	}
    }

    private void setNativeSequence(final org.biojava.bio.symbol.SymbolList symbols)
    {
	nativeSequence = new BioJavaSequence(symbols);
    }
}
