$: << 'web-socket-ruby/lib'

require 'app'
require 'json'
require 'web_socket'

if !ARGV[0]
  STDERR.puts "Usage: #$0 <module>"
  exit
end
require ARGV[0]
app = newApp

server = WebSocketServer.new("ws://localhost:10081",
                             :host => "0.0.0.0",
                             :accepted_domains => "*")
#                             :policy => File.read('sock_policy.xml'))
puts("Ready")

Thread.new {
  objs = []

  while true
    begin
      app.onTimer

    rescue
      puts $!
      puts $!.backtrace
    end

    sleep 0.03
  end
}

server.run() do |ws|
  puts("Connection accepted")
  puts("Path: #{ws.path}, Origin: #{ws.origin}")
  if ws.path == "/"
    ws.handshake()

    app.onOpen(ws)

#     @ws[ws] = st = State.new
    while data = ws.receive()
      #printf("Received: %p\n", data)
      #ws.send(data)
      #printf("Sent: %p\n", data)

      #cmd, *args = data.split(' ')
      cmd, *args = JSON.parse(data)
      case cmd
      when 'move'
        x = args[0].to_i
        y = args[1].to_i
        app.onMouseMove(ws, x, y)
      when 'down'
        x = args[0].to_i
        y = args[1].to_i
        app.onMouseDown(ws, x, y)
      when 'up'
        x = args[0].to_i
        y = args[1].to_i
        app.onMouseUp(ws, x, y)
      when 'msg'
        app.onMessage(ws, args)
      end
    end
#     @ws.delete(ws)

    app.onClose(ws)
  else
    ws.handshake("404 Not Found")
  end
  puts("Connection closed")
end
