# -*- mode: perl; coding: utf-8 -*-
# POE::Filter::HTTPD::Keitairc
#
# Copyright (c) 2010 ISHIKAWA Mutsumi <ishikawa@hanzubon.jp>
# This program is covered by the GNU General Public License 2

package POE::Filter::HTTPD::Keitairc;
use POE::Filter::HTTPD;
use HTTP::Response;

use strict;
use warnings;

use base qw(POE::Filter::HTTPD);

my $_STRM_IDX = 6;
sub STRM() { $_STRM_IDX } # raw data buffer to build requests

sub new {
	my $class = shift;
	my $me = POE::Filter::HTTPD->new;
	$_STRM_IDX = $#{$me} + 1;
	$me->[STRM] = '';

	return bless $me, $class;
}

sub get_one_start {
	my ($me, $stream) = @_;
	$me->SUPER::get_one_start($stream);
	$me->[STRM] .= join('', @$stream);
}

sub get_one {
	my ($me) = @_;
	my $req = [];

	if ($me->[STRM] =~ /^(?:\x00(.*)\xff|\xff\x00)$/) {
		$req = [$1];
		$me->[STRM] = '';
	} else {
		$req = $me->SUPER::get_one();

		if(defined $req->[0]) {
			if ($req->[0]->header('Upgrade')
			    && $req->[0]->header('Upgrade') eq 'WebSocket'
			    && $req->[0]->header('Connection')
			    && $req->[0]->header('Connection') eq 'Upgrade') {
				if ($me->[STRM] =~ /\r\n\r\n(.{8})$/) {
					$req->[0]->content($1);
				}
			}
			$me->[STRM] = '';
		}
	}

	return $req;
}

sub get_pending {
	my ($me) = @_;
	if (length($me->[STRM])) {
		my $buf = $me->[STRM];
		$me->[STRM] = '';
		return [$buf];
	} else {
		return undef;
	}
}

1;
