puts "LOADING INSTRUMENTATION::RACK::REQUEST TIMER"


require 'rack/request'

module Ubiquity
  module Api
    module Instrumentation
      module Rack
        class RequestTimer

          if Ubiquity::Api.respond_to?(:register)
            puts "REGISTER RACK ADAPTER: Ubiquity::Api::Instrumentation::Rack::RequestTimer"
            Ubiquity::Api.register do |config|
              config.middleware(self)
            end
          end

          class << self
            def register(app)
              app.use Ubiquity::Api::Instrumentation::Rack::RequestTimer
            end
          end # self

          attr_accessor :app, :opts

          ##
          # Create a rack filter
          ##
          def initialize(app, opts = {})
            @app = app
            @opts = opts
          end

          ##
          # Call the rack filter
          ##
          def call(env)
            start = Time.now
            status, headers, body = app.call(env)
            stop = Time.now
            delta = (stop - start) * 1000.0
            Ubiquity::Api::Logger.log  "#{env['REQUEST_URI']}  : len=#{body.length} bytes, duration=#{delta} ms "
            [status, headers, body]
          end


        end
      end
    end
  end
end
