#!/usr/local/bin/ruby
####################################################################
# user.rb
# This is a partial implemntation o the demo program user distributed
# with Spread, rewritten in ruby.
# Copyright(2001) George Schlossnagle
# Re-written by Ned Konz
####################################################################
$:.unshift('.')
require 'spread_nonblock'

$stdout.sync = true
print "What name would you like to go by?> "
name = gets.chomp!
print "What group would you like to join?> "
group = gets.chomp!
puts "Type q by itself to quit"

conn = Spread.new("4803", name, true);

class Spread
  def receive_wait(timeout = nil)
     @mbox_io = IO.new(mbox(), 'r') unless @mbox_io
    return IO.select([ @mbox_io ], nil, nil, timeout)
  end
end

recv_thread = Thread.new(conn) do
  | conn |
  bytes = 0
  mess = nil
  while(1)
    conn.receive_wait
    while conn.poll > 0
      mess = conn.receive
      if mess.is_regular
        puts "#{ mess.sender } says #{ mess.message }"
      else
        reason = mess.is_caused_by_join ? 'join' : 'leave'
        puts "#{reason} membership from #{mess.sender}: #{ mess.groups.join(',') }"
      end
      print "User> "
    end
  end	
end

conn.join(group)

while(1)
  print "User> "
  send_mess = gets.chomp!
  if send_mess == "q"
    break
  elsif send_mess != ""
    conn.multicast(send_mess, group, Spread::RELIABLE_MESS)
  end
end

Thread::kill(recv_thread)
conn.disconnect
