package HTTP::Engine::Interface::PSGI;
use HTTP::Engine::Interface
    builder => 'CGI',
    writer  => {
        around => {
            finalize => sub { _finalize(@_) },
        },
    },
;

sub can_has_streaming { 1 }

sub run {
    my($self, $env) = @_;

    # get PSGI response arrayrey. generated by _finalize
    $self->handle_request(
        _connection => {
            env           => $env,
            input_handle  => $env->{'psgi.input'},
            output_handle => undef,
        },
    );
}

# generate PSGI response
# hack to HTTP::Engine::Role::ResponseWriter::Finalize
sub _finalize {
    my($next, $writer, $req, $res) = @_;
    my @headers; $res->headers->scan(sub {
        my ($k, $v) = @_;
        # PSGI spec says "The header MUST NOT contain a Status key".
        if ($k eq 'Status') {
            return if $res->code eq $v;
            die "Do not set Status header with HTTP::Engine::Interface::PSGI.";
        }
        push @headers, $k, $v;
    });
    my $body = $res->body;
    $body = [ $body ] unless ref($body);
    [ $res->code, \@headers, $body ];
}

__INTERFACE__

__END__

=for stopwords PSGI

=head1 NAME

HTTP::Engine::Interface::PSGI - PSGI interface for HTTP::Engine

=head1 SYNOPSIS

use L<Plack> for L<PSGI> Impl

  use HTTP::Engine;
  use Plack::Loader;
  my $engine = HTTP::Engine->new(
      interface => {
          module => 'PSGI',
          request_handler => sub {
              HTTP::Engine::Response->new( body => 'ok' );
          },
      },
  );
  my $app = sub { $engine->run(@_) };
  Plack::Loader->load('Standalone', port => 801)->run($app); # see L<Plack::Server::Standalone> and  L<Plack::Loader>

if you want streaming response

  use HTTP::Engine;
  use IO::Handle::Util qw(io_from_getline); # see L<IO::Handle::Util>
  use Plack::Loader;
  my $count = 1;
  my $engine = HTTP::Engine->new(
      interface => {
          module => 'PSGI',
          request_handler => sub {
              HTTP::Engine::Response->new( body => io_from_getline { return "count: " . $count++ } );
          },
      },
  );
  my $app = sub { $engine->run(@_) };
  Plack::Loader->load('AnyEvent', port => 801)->run($app); # see L<Plack::Server::AnyEvent>


=head1 AUTHOR

yappo

=head1 SEE ALSO

L<PSGI>

=head1 LICENSE

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut