#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RSApache::Message;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::Assert;
use Common::WriteXML;

use Data::Dumper;

sub new {
    my ( $class, %args ) = @_;

    my $self = bless {}, $class;

    return $self->_init(%args);
}

sub _init {
    my ( $self, %args ) = @_;

    if ( exists $args{string} ) {
        return $self->_initFromString( $args{string} );
    } elsif ( exists $args{type} && exists $args{code} ) {
        return $self->_initFromTypeAndCode( $args{type}, $args{code} );
    }

    # Can't create this object without some sort of state...
    #
    assert(0);

    return undef;
}

sub _initFromString {
    my ( $self, $string ) = @_;

    assert( defined $string );

    my ( $type, $code ) = split( /\|/, $string );
    return $self->_initFromTypeAndCode( $type, $code );
}

sub _initFromTypeAndCode {
    my ( $self, $type, $code ) = @_;

    assert( defined $type );
    assert( defined $code );

    $self->{Type} = $type;
    $self->{Code} = $code;

    return $self;
}

# !!! This is almost _identical_ to the XMLObject version.
# !!! They should share a base class, eh?
#
sub writeXML {
    my ( $self, $xw, $tag, %extraParams ) = @_;

    if ($tag) {
        $xw->starttag( $tag, %extraParams );
    }

    foreach my $key ( keys %{$self} ) {
        next if ( '_' eq substr( $key, 0, 1 ) );
        Common::WriteXML::writeXML( $xw, $self->{$key}, $key );
    }

    if ($tag) {
        $xw->endtag($tag);
    }
}

sub toString {
    my ($self) = @_;

    return $self->{Type} . "|" . $self->{Code};
}

# +----------------+
# | static methods |
# +----------------+

# This method is intended to receive an array of strings (say, from CGI).
#
sub ArrayRefToMessageList {
    my ($arrayRef) = @_;

    return undef unless defined $arrayRef;

    my $list = $arrayRef;
    $list = [$list] if 'ARRAY' ne ref($list);

    my @outList;
    foreach my $string (@$list) {
        push @outList, RSApache::Message->new( string => $string );
    }

    return { Message => \@outList };
}

###
1;    #
###
