package AnyEvent::FCGI::Request;

=head1 NAME

AnyEvent::FCGI::Request - a single FastCGI request handle for L<AnyEvent::FCGI>

=head1 SYNOPSIS

    use AnyEvent;
    use AnyEvent::FCGI;
    use CGI::Stateless;
    
    my $fcgi = new AnyEvent::FCGI(
        port => 9000,
        on_request => sub {
            my $request = shift;
            
            local *STDIN; open STDIN, '<', \$request->read_stdin;
            local %ENV = %{$request->params};
            local $CGI::Q = new CGI::Stateless;
            
            $request->respond(
                'Hello, ' . (CGI::param('name') || 'anonymous'),
                'Content-Type' => 'text/html; charset=utf8',
                'Set-Cookie' => 'cookie_a=1; path=/',
                'Set-Cookie' => 'cookie_b=2; path=/',
            );
        }
    );
    
    AnyEvent->loop;

=head1 DESCRIPTION

This is the request object as generated by L<AnyEvent::FCGI>.
When given to the controlling program, each request will already have its parameters and STDIN data.
The program can then write response data to the STDOUT stream,
messages to the STDERR stream, and eventually finish it.

This module would not be used directly by a program using C<AnyEvent::FCGI>, but
rather, objects in this class are passed into the C<on_request> callback of
the containing C<AnyEvent::FCGI> object.

=cut

use strict;
use warnings;

use Scalar::Util qw/weaken/;

sub new {
    my ($class, %params) = @_;
    
    my $self = bless {
        id => $params{id},
        fcgi => $params{fcgi},
        connection => $params{connection},
        flags => $params{flags},
        
        stdin => '',
        stdin_done => 0,
        params => {},
        params_string => '',
        params_done => 0,
        
        used_stderr => 0,
    }, $class;
    
    weaken($self->{fcgi});
    weaken($self->{connection});

    return $self;
}

sub _ready_check {
    my $self = shift;
    
    if ($self->{stdin_done} && $self->{params_done} && $self->{fcgi}) {
        $self->{fcgi}->_request_ready($self);
    }
}

sub _process_stdin_record {
    my ($self, $record) = @_;

    if ($record->{length}) {
        $self->{stdin} .= $record->{content};
    } else {
        $self->{stdin_done} = 1;
    }

    $self->_ready_check;
}

sub _process_params_record {
    my ($self, $record) = @_;
    
    if ($record->{length}) {
        $self->{params_string} .= $record->{content};
    } else {
        $self->{params_done} = 1;
        
        my $data = $self->{params_string};
        
        while (length $data) {
            my ($name_length, $value_length);
            foreach my $length ($name_length, $value_length) {
                ($length) = unpack('C', $data);
                if ($length & 0x80) {
                    ($length) = unpack('N', $data);
                    $length &= 0x7FFFFFFF;
                    substr($data, 0, 4, '');
                } else {
                    substr($data, 0, 1, '');
                }
            }
            my $name = substr($data, 0, $name_length, '');
            my $value = substr($data, 0, $value_length, '');
            $self->{params}->{$name} = $value;
        }
        
        $self->{params_string} = '';
    }
    
    $self->_ready_check;
}

sub _send_record {
    my ($self, $record) = @_;
    
    if ($self->is_active) {
        $self->{connection}->send_record($record);
    } else {
        warn 'Cannot respond to inactive request';
    }
}

sub _print_stream {
    my ($self, $data, $stream) = @_;

    while (length $data) {
        my $chunk = substr($data, 0, AnyEvent::FCGI::Connection->MAX_DATA_SIZE, '');
        $self->_send_record({
            request_id => $self->{id},
            type => $stream,
            content => $chunk,
        });
    }
}

=head1 METHODS

=head2 is_active

Returns false if the webserver has already closed the control connection.
No further work on this request is necessary, as it will be discarded.

This method can be used if response will not be sent immediately from C<on_request> callback.

=cut

sub is_active {
    return defined shift->{connection};
}

=head2 param($key)

This method returns the value of a single request parameter, or C<undef> if no such key exists.

=cut

sub param {
    my ($self, $key) = @_;
    
    return $self->{params}->{$key};
}

=head2 params

This method returns a reference to a hash containing a copy of the request
parameters that had been sent by the webserver as part of the request.

=cut

sub params {
    my ($self) = @_;
    
    return {%{$self->{params}}};
}

=head2 read_stdin($size)

This method works similarly to the C<read(HANDLE)> function. It returns the
next block of up to $size bytes from the STDIN buffer. If no data is available
any more, then C<undef> is returned instead.

=cut

sub read_stdin {
    my ($self, $size) = @_;
    
    $size ||= length $self->{stdin};
    
    return length $self->{stdin} ? substr($self->{stdin}, 0, $size, '') : undef;
}

=head2 print_stdout($data)

This method appends the given data to the STDOUT stream of the FastCGI
request, sending it to the webserver to be sent to the client.

=cut

sub print_stdout {
    my ($self, $data) = @_;
    
    $self->_print_stream($data, AnyEvent::FCGI->FCGI_STDOUT);
}

=head2 print_stderr($data)

This method appends the given data to the STDERR stream of the FastCGI
request, sending it to the webserver.

=cut

sub print_stderr {
    my ($self, $data) = @_;
    
    $self->{used_stderr} = 1;
    $self->_print_stream($data, AnyEvent::FCGI->FCGI_STDERR);
}

=head2 finish

When the request has been dealt with, this method should be called to indicate
to the webserver that it is finished. After calling this method, no more data
may be appended to the STDOUT stream.

=cut

sub finish {
    my ($self) = @_;
    
    if ($self->is_active) {
        $self->_send_record({
            request_id => $self->{id},
            type => AnyEvent::FCGI->FCGI_STDOUT,
            content => '',
        });
        
        $self->_send_record({
            request_id => $self->{id},
            type => AnyEvent::FCGI->FCGI_STDERR,
            content => '',
        }) if $self->{used_stderr};
        
        $self->_send_record({
            request_id => $self->{id},
            type => AnyEvent::FCGI->FCGI_END_REQUEST,
            content => pack('Ncccc', 0, AnyEvent::FCGI->FCGI_REQUEST_COMPLETE, 0, 0, 0),
        });
        
        $self->{connection}->{io}->push_shutdown unless $self->{flags} & AnyEvent::FCGI->FCGI_KEEP_CONN;
        
        delete $self->{connection}->{requests}->{$self->{id}};
        delete $self->{connection};
    } else {
        warn 'Cannot finish inactive request';
    }
}

=head2 respond($content, @headers)

This method sends the response to the webserver and finishes the request.
HTTP reply code can be specified in C<Status> header (200 by default).
This method can be used instead of C<print_stdout> and C<finish>.

=cut

sub respond {
    my ($self, $content, @headers) = @_;
    
    if ($self->is_active) {
        my $has_status;
        my $output = '';
        
        while (scalar @headers) {
            my $header = shift @headers;
            $has_status = 1 if $header eq 'Status';
            $output .= $header . ': ' . shift(@headers) . "\n";
        }
        $output .= "Status: 200 OK\n" unless $has_status;
        $output .= "\n$content";
        
        $self->print_stdout($output);
        $self->finish;
    } else {
        warn 'Cannot respond to inactive request';
    }
}

1;
