class SpadeClient

  TIMEOUT = begin
    Settings.spade.timeout
  rescue Settingslogic::MissingSetting
    60
  end

  DISABLED = begin
    Settings.activity_log.disable
  rescue Settingslogic::MissingSetting
    false
  end

  def self.send_event(attributes)
    return if DISABLED

    # grab everything except the event itself to use as the event's properties
    properties = attributes.except(:event)

    # construct a real event hash with properties as a sub hash
    event_object = {
      event: attributes[:event],
      properties: properties
    }

    # base64 encode the json version of the event object
    encoded_event_object = Base64.encode64(event_object.to_json)

    conn = Faraday.new(url: Settings.spade.endpoint, request: { open_timeout: self::TIMEOUT }) do |faraday|
      faraday.use Service::ResponseLogger
      faraday.request  :url_encoded
      faraday.adapter  Faraday.default_adapter
    end

    begin
      # post it to the tracking endpoint for spade to consume
      conn.post '/track', { data: encoded_event_object }
    rescue Faraday::Error => e
      Rails.logger.error(e)
    end
  end
end
