package Bio::Phylo::Annotation;
use strict;
use Bio::Phylo::Util::XMLWritable;
use Bio::Phylo::Util::CONSTANT qw(_ANNOTATION_ _DICTIONARY_);
use vars '@ISA';
use UNIVERSAL qw'can isa';
use Bio::Phylo::Util::Exceptions 'throw';
@ISA=qw(Bio::Phylo::Util::XMLWritable);
{
    my @fields = \( my ( %key, %datatype, %value ) );
    my $TYPE_CONSTANT = _ANNOTATION_;
    my $CONTAINER_CONSTANT = _DICTIONARY_;

=head1 NAME

Bio::Phylo::Annotation - Segment in an object to annotate other objects with.

=head1 SYNOPSIS

 use Bio::Phylo::Factory;
 my $fac = Bio::Phylo::Factory->new;
 # there are several data types: string, integer, float, uri, any, etc.
 # refer to nexml.org for a complete list
 my $dic = $fac->create_dictionary( -tag => 'string' );
 my $ann = $fac->create_annotation( -value => 'This is a description' );
 $dic->insert( $ann );
 print $dic->to_xml;

 # prints: <dict><string id="string2">This is a description</string></dict>

=head1 DESCRIPTION

To comply with the NeXML standard (L<http://www.nexml.org>), Bio::Phylo implements
dictionary annotations, which consist conceptually of key/value pairs where the
key is an xml id (which is either autogenerated or can be set using the set_xml_id
method) and the value is the containing element (whose name specifies the data
type of its text contents, i.e. string, integer, float and so on).

This class implements a single key/value pair, of which multiples can be inserted
in a dictionary to create a data structure that is serialized to something akin
to a hash. The dictionary can be attached to any of the subclasses of
L<Bio::Phylo::Util::XMLWritable>.

Of note is the fact that annotations can has different xml tag names, where the 
name specifies the data type of the annotation text content. For example, if you 
set the tag name to 'string' (i.e. $ann->set_tag('string')) then the value is 
interpreted to be a string (i.e. $ann->set_value('some kind of string')). Also,
a common tag name is 'any', which means that the value is any kind of xml structure,
which can be provided as a raw string, or as an xml element tree object of one of 
the following distributions: L<XML::DOM>, L<XML::GDOME>, L<XML::Twig>, L<XML::DOM2>,
L<XML::DOMBacked>, L<XML::Handler>, L<XML::Element>, L<XML::API>, L<XML::Code> or
L<XML::XMLWriter>. Alternatively, you can provide a L<RDF::Core::Model> for
semantic annotations or a L<Bio::Phylo::Dictionary> to create recursively nested
dictionaries. 

=head1 METHODS

=head2 CONSTRUCTOR

=over

=item new()

 Type    : Constructor
 Title   : new
 Usage   : my $anno = Bio::Phylo::Annotation->new;
 Function: Initializes a Bio::Phylo::Annotation object.
 Returns : A Bio::Phylo::Annotation object.
 Args    : optional constructor arguments are key/value
 		   pairs where the key corresponds with any of
 		   the methods that starts with set_ (i.e. mutators) 
 		   and the value is the permitted argument for such 
 		   a method. The method name is changed such that,
 		   in order to access the set_value($val) method
 		   in the constructor, you would pass -value => $val

=cut

    sub new {
        return shift->SUPER::new( '-tag' => 'string', @_ );     
    }

=back

=head2 MUTATORS

=over

=item set_value()

Sets the annotation value, e.g. for an annotation with tag 'string',
this would be a free form string, such as a description.

 Type    : Mutator
 Title   : set_value
 Usage   : $anno->set_value('this is a description');
 Function: Sets the annotation value
 Returns : Modified object.
 Args    : A valid argument is whatever is valid for the annotation
           data type.

=cut

    sub set_value {
        my ( $self, $value ) = @_;
        $value{ $self->get_id } = $value;
        return $self;
    }

=back

=head2 ACCESSORS

=over

=item get_value()

Gets invocant's value.

 Type    : Accessor
 Title   : get_value
 Usage   : my $val = $anno->get_value;
 Function: Gets invocant's value.
 Returns : The specified value, whose data type depends on the 
           xml tag name.
 Args    : NONE

=cut

    sub get_value {
        my $self = shift;
        return $value{ $self->get_id };
    }

=back

=head2 SERIALIZERS

=over

=item to_xml()

Serializes object to an xml string

 Type    : Serializer
 Title   : to_xml()
 Usage   : print $ann->to_xml();
 Function: Serializes object to xml string
 Returns : String 
 Args    : None
 Comments:

=cut

    sub to_xml {
        my $self = shift;
        my $key = $self->get_xml_id;
        my $xml = '';
        my $value = $self->get_value;
        if ( ref($value) ) {

        	# for RDF::Core::Model objects
        	if ( isa($value, 'RDF::Core::Model') ) {
        		eval {
        			require RDF::Core::Model::Serializer;
        			my $serialized_model = '';
  					my $serializer = RDF::Core::Model::Serializer->new(
  						'Model'  => $value,
                        'Output' => \$serialized_model,
                        # BaseURI => 'URI://BASE/',
                    );   
                    $value = $serialized_model;     			
        		};
        		if ( $@ ) {
        			throw 'API' => $@;
        		}
        	}         
        	
        	# for XML::XMLWriter object
        	elsif ( isa($value, 'XML::XMLWriter') ) {
        		$value = $value->get;
        	}
        	
        	else {
        		my $concatenated = '';
        		my ( @values, @raw_values );
        		if ( ref($value) eq 'ARRAY' ) {
        			@values = @{ $value };
        		}
        		else {
        			push @values, $value;
        		}
        		for my $v ( @values ) {
	        		# duck-typing
		        	# Bio::Phylo => to_xml, XML::DOM,XML::GDOME => toString, XML::Twig => sprint
		        	# XML::DOM2 => xmlify, XML::DOMBacked => as_xml,
		        	# XML::Handler => dump_tree, XML::Element => as_XML
		        	# XML::API => _as_string, XML::Code => code
		        	
		        	if ( ref($v) ) {
			        	my @methods = qw(to_xml toString sprint _as_string code xmlify as_xml dump_tree as_XML);
			        	SERIALIZER: for my $method ( @methods ) {
			        		if ( can($v,$method) ) {
			        			$concatenated .= $v->$method;
			        			last SERIALIZER;
			        		}
			        	}
		        	}
		        	else {
		        		push @raw_values, $v;
		        	}
        		}
        		$value = scalar(@raw_values) ? join(' ',@raw_values) : $concatenated;
        	}
        }
        my $type = $self->get_tag;
        $xml .= "<${type} id=\"${key}\">" . $value . "</${type}>";
        return $xml;
    }
    
=back

=head1 SEE ALSO

=over

=item L<Bio::Phylo::Dictionary>

Annotation objects are combined into a dictionary.

=item L<Bio::Phylo::Util::XMLWritable>

This object inherits from L<Bio::Phylo::Util::XMLWritable>, so methods
defined there are also applicable here.

=item L<Bio::Phylo::Manual>

Also see the manual: L<Bio::Phylo::Manual> and L<http://rutgervos.blogspot.com>.

=back

=head1 REVISION

 $Id: Annotation.pm 604 2008-09-05 17:32:28Z rvos $

=cut
    
    sub _type { $TYPE_CONSTANT }
    sub _container { $CONTAINER_CONSTANT }
    sub _cleanup {
        my $self = shift;
        my $id = $self->get_id;
        for my $field ( @fields ) {
            delete $field->{$id};
        }
    }    
}
1;