class Slack::RealTime::Client

def close(_event)

def close(_event)
  @socket = nil
  EM.stop
end

def dispatch(event)

def dispatch(event)
  return false unless event.data
  data = JSON.parse(event.data)
  type = data['type']
  return false unless type
  callbacks = @callbacks[type.to_s]
  return false unless callbacks
  callbacks.each do |c|
    c.call(data)
  end
  true
end

def initialize

def initialize
  @callbacks = {}
  @web_client = Slack::Web::Client.new
end

def on(type, &block)

def on(type, &block)
  type = type.to_s
  @callbacks[type] ||= []
  @callbacks[type] << block
end

def open(_event)

def open(_event)
end

def send_json(data)

def send_json(data)
  fail ClientNotStartedError unless started?
  @socket.send_data(data.to_json)
end

def start!

def start!
  fail ClientAlreadyStartedError if started?
  EM.run do
    @options = web_client.rtm_start
    @socket = Slack::RealTime::Socket.new(@options['url'])
    @socket.connect! do |ws|
      ws.on :open do |event|
        open(event)
      end
      ws.on :message do |event|
        dispatch(event)
      end
      ws.on :close do |event|
        close(event)
      end
    end
  end
end

def started?

def started?
  @socket && @socket.connected?
end

def stop!

def stop!
  fail ClientNotStartedError unless started?
  @socket.disconnect! if @socket
end