#!/usr/bin/env perl

use Mojolicious::Lite;

use lib '/srv/MojoX-Gearman/lib';
use MojoX::Gearman;

use Data::Dump qw(dump);

# Documentation browser under "/perldoc" (this plugin requires Perl 5.10)
plugin 'pod_renderer';

get '/' => sub {
	my $self = shift;
	$self->render('index');
};

get '/ping_http' => sub {
	my $self = shift;
	my $gearman = $self->client;
	my $pong = $gearman->post( "http://localhost:4780/ping" => { Connection => 'close' } => "some data" )->res->body;
	warn "ping = $pong";
	$self->render( 'ping', pong => $pong );
};

my $gearman = MojoX::Gearman->new; #( ioloop => Mojo::IOLoop->singleton );
$gearman->server( $ENV{GEARMAN} || 'localhost:4730' );

get '/ping_g' => sub {
	my $self = shift;
	my $pong = $gearman->req( 'SUBMIT_JOB', 'ping', '', "some data 2" );
	warn "ping = $pong";
	$self->render( 'ping', pong => $pong );
};

sub _render_jsonp {
	my ( $self, $json ) = @_;
	#my $data = $self->render( json => $json, partial => 1 );
	my $data = $json;
	if ( my $callback = $self->param('callback') ) {
		$data = "$callback($data)";
	}
	$self->render( data => $data, format => 'js' );
}


get '/g/:call/:args' => [ args => qr/.*/ ] => sub {
	my $self = shift;
	my $ret = $gearman->req( 'SUBMIT_JOB', $self->param('call'), '', $self->param('args') );
	warn $self->param('call'), " = ", dump($ret), "\n";
	die "no result for ", $self->param('call'), ' args: ', $self->param('args') unless defined $ret;
	_render_jsonp( $self, $ret );
};

get '/_g/status' => sub {
	my $self = shift;

	my $ret = $gearman->req( 'TEXT' => 'status' );
	warn "# status:\n$ret";

	my @c = qw(function total running available);

	my $status;
	foreach my $l ( split(/\n/,$ret) ) {
		my @v = split(/\t/, $l);
		my $h;
		$h->{$c[$_]} = $v[$_] foreach 0 .. $#v;
		push @$status, $h;
	}
	warn "## ", dump $status;
	_render_jsonp( $self, Mojo::JSON->new->encode({ status => $status }) );
};

app->start;
__DATA__

@@ index.html.ep
% layout 'default';
% title 'Gearman demo';

<ul>
<li><a href="/gearman.html#ping/127.0.0.1">Gearman</a> web interface
<li><%= link_to 'CRM' => 'CRM.html' %> search with tabular output
</ul>

Low-level API tests:

<%= link_to 'HTTP ping' => 'ping_http' %>
<%= link_to 'Gearman ping' => 'ping_g' %>

@@ ping.html.ep
% layout 'default';
pong: <tt><%= $pong %>

@@ dump.html.ep
% layout 'default';
<pre><%= $dump %></pre>

@@ layouts/default.html.ep
<!doctype html><html>
  <head><title><%= title %></title></head>
  <body><%= content %></body>
</html>
