#Copyright Massachusetts Institute of technology, 2000.
#Written by Eric Prud'hommeaux for the World Wide Web Consortium

# $Id: Message.pm,v 1.5 2004/06/09 09:19:06 eric Exp $

use strict;

package W3C::Http::Message;

use W3C::Util::Object;

use vars qw($VERSION $REVISION @ISA @EXPORT @EXPORT_OK);
@ISA = qw(W3C::Util::NamedParmObject);
$VERSION = 1.0;

sub new {
    my ($proto, @parms) = @_;
    my $class = ref($proto) || $proto;
    my $self = $class->SUPER::new(@parms);
    $self->missingParm('-statusCode') if (!$self->{-statusCode});
    $self->missingParm('-headers') if (!$self->{-headers});
    $self->missingParm('-body') if (!exists $self->{-body});
    return $self;
}

sub addHeader {
    my ($self, $header, $value) = @_;
    push (@{$self->{-headers}}, [$header, $value]);
}

sub toString {
    my ($self) = @_;
    my (@ret, $contentLength, $contentType);
    push (@ret, "Status: $self->{-statusCode}");
    foreach my $header (@{$self->{-headers}}) {
	if ($header->[0] =~ m/^Content-length$/i) {
	    $contentLength = $header->[1];
	} elsif ($header->[0] =~ m/^Content-type$/i) {
	    $contentType = $header->[1];
	}
	push (@ret, "$header->[0]: $header->[1]");
    }
    push (@ret, 'Content-length: '. length $self->{-body}) if (!defined $contentLength);
    push (@ret, 'Content-type: text/html') if (!defined $contentType);
    push (@ret, '');
    push (@ret, $self->{-body});
    return join ("\n", @ret);
}

sub getBody {
    my ($self) = @_;
    return $self->{-body};
}

1;

__END__

=head1 NAME

W3C::Http::Message - HTTP Request or Response Message

=head1 SYNOPSIS

    use W3C::Http::Message;
    print STDOUT Message(-statusCode => 200
        -headers => {}, 
        -body => "
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head><title>Hi</title></head>
        <body><h1>Hi</h1></body>
    </html>"));
    }

=head1 DESCRIPTION

This is a convient exception to return an W3C::Http::Message (or whatever was passed in as the B<-httpMessage> parameter). Its B<toString> method returns a valid HTTP message. This is most usefull in scenarios where the script has a variety of return points, as is common in scripting where the server may return messages like AuthReqired or Redirect instead of serving the requested content.

=head2 Constructor ( PARMS )

Where PARMS are:
  C<-statusCode>: HTTP Status Codes ala 200, 401, 403...
  C<-headers>: Hash table of headers
  C<-body>: text body of the HTTP message to send

This module is part of the W3C::Http CPAN module.

=head1 AUTHOR

Eric Prud'hommeaux <eric@w3.org>

=head1 SEE ALSO

L<W3C::Http::MessageException>

=cut
