#!/usr/local/bin/perl -w
###########################################
# cntdown-random
# Mike Schilli, 2011 (m@perlmeister.com)
###########################################
use strict;
use Mojolicious::Lite;
use Mojo::IOLoop;

my $listen = "http://localhost:8083";
@ARGV = (qw(daemon --listen), $listen);

my $loop = Mojo::IOLoop->singleton();

###########################################
websocket "/myws" => sub {
###########################################
  my($self) = @_;

  my $timer_cb;
  my $counter = 10;

  $timer_cb = sub {
    $self->send_message( "$counter" );
    if( $counter-- > 0 ) {
        $loop->timer(rand(1), $timer_cb);
    } else {
        $self->send_message( "BOOM!" );
    }
  };

  $timer_cb->();
};

###########################################
get '/' => sub {
###########################################
  my ($self) = @_;

  ( my $ws_url = $listen ) =~ s/^http/ws/;
  $ws_url .= "/myws";
  $self->{stash}->{ws_url} = $ws_url;
} => 'index';

app->start();

__DATA__
@@ index.html.ep
% layout 'default';
Random counter:
<font size=+2 id="counter"></font>

@@ layouts/default.html.ep
<!doctype html><html>
  <head><title>Random Countdown</title>
    <script type="text/javascript">
      var socket = new WebSocket( 
                     "<%== $ws_url %>" );
      socket.onmessage = function (msg) {
        document.getElementById( 
          "counter").innerHTML = msg.data;
      };
    </script>
  </head>
  <body> <%== content %> </body>
</html>
