require 'drb/drb'
require "readline"

DRb.start_service

phrase = ARGV.shift
front = DRbObject.new(nil, ARGV.shift||'druby://localhost:12345')

server = front.server(phrase)

while line = Readline::readline("rbip: ", true)
  command = line.chomp.split(" ")
  next if command.size <= 0

  case command[0]
  when "list"
    server.members.each do |host, info|
      nick = info['nickname']
      group = info['group']
      addr = info['addr']
      absence = info['absence']

      str = "#{nick}(#{group}) #{host}(#{addr})"
      if command[1] 
	puts str if str.index(command[1])
      else
	puts str
      end
    end

  when "send"
    server.send_msg(command[1], command[2..-1].join(' '), true)

  when "absence"
    server.absence("Absence!!!", true)

  when "here"
    server.absence(nil, false)

  when "logout"
    server.logout
    exit

  when "history"
    members = server.members
    server.history do |history|
      puts("* " + history.time.to_s)
      puts("* " + history.host)
      puts(history.msg)
    end

  when 'sort'
    server.sorted_members(command[1]) do |host, info|
      nick = info['nickname']
      group = info['group']
      addr = info['addr']
      absence = info['absence']
	
      puts "#{nick}(#{group}) #{host}(#{addr})"
    end

  when 'recent'
    server.recent.each do |host, info|
      nick = info['nickname']
      group = info['group']
      addr = info['addr']
      absence = info['absence']
	
      puts "#{nick}(#{group}) #{host}(#{addr})"
    end

  when 'ack'
    server.send_ack(command[1])

  when 'add_broadcast'
    server.add_broadcast(command[1])

  when 'login'
    server.login

  when 'update_recent'
    server.update_recent

  when 'msg'
    server.msg_holder.each do |msg|
      puts "From: #{msg.from_addr}"
      puts "Key: #{msg.key}"
      puts "----------"
      puts msg.message
      puts "----------"
    end

  when 'open'
    msg = server.msg_holder[command[1]]
    msg.open if msg

  else
    puts "syntax error"
  end
end
