begin
  require 'faye/websocket'
  require 'eventmachine'
rescue LoadError
  p 'Installing dependencies...'
  `gem install faye-websocket`
  `gem install eventmachine`
  require 'faye/websocket'
  require 'eventmachine'
end

class SafeArray < Array
  def each(&block)
      return self.dup.to_a.each(&block)
  end
end

class SafeHash < Hash
  def each(&block)
      return self.dup.to_h.each(&block)
  end
end

require_relative './Message_Parser.rb'
require_relative './Users.rb'

Dir["./Extensions/*.rb"].each {|file| require file }

EM.run {
  $ws = Faye::WebSocket::Client.new('ws://sim.smogon.com:8000/showdown/websocket')

  $ws.on :open do |event|
    p 'Connected to Pokemon Showdown!'
    Users.prune_users
  end

  $ws.on :message do |event|
    begin
      Message_Parser.parse(event.data)
    rescue => error
      p error.message, error.backtrace
    end
  end

  $ws.on :close do |event|
    p "Disconnected from Pokemon Showdown!"
    $ws = nil
    exit!
  end
}
