<%args>
$forever => 1
</%args>
<%init>

Jifty->web->response->content_type("text/html; charset=utf-8");
Jifty->web->response->header('Pragma' => 'no-cache');
Jifty->web->response->header('Cache-control' => 'no-cache');
Jifty->handler->send_http_header;

my $writer = XML::Writer->new;
$writer->xmlDecl( "UTF-8", "yes" );

my $begin = <<'END';
<!DOCTYPE html>
<html><head><title></title></head>
END
chomp $begin;

if ($forever) {
    my $whitespace = " " x ( 1024 - length $begin );
    $begin =~ s/<body>$/$whitespace<body>/s;
}

$m->print($begin);
$m->flush_buffer;
Jifty->handler->buffer->flush_output;
$writer->startTag("body");

local $SIG{PIPE} = sub {
    die "ABORT";
};

my $loops;
while (Jifty->config->framework('PubSub')->{'Enable'}) {
    Jifty->web->out(" ") if ++$loops % 10 == 0;
    my $sent = write_subs_once($writer);
    Jifty->handler->buffer->flush_output;
    flush STDOUT;
    last if ( $sent && !$forever );
    sleep 1;
}
$writer->endTag();
return;

sub write_subs_once {
    my $writer = shift;
    Jifty::Subs::Render->render(
        Jifty->web->session->id,
        sub {
            my ( $mode, $name, $content, $attrs ) = @_;
            $writer->startTag( "pushfrag", mode => $mode, %{$attrs || {}} );
            $writer->startTag( "fragment", id   => $name );
            $writer->dataElement( "content", $content );
            $writer->endTag();
            $writer->endTag();
        }
    );
}
</%init>
