module BackendClient
  class Service
    module LogRequests

      def delete_all_log_requests
        delete("#{url_prefix}/log_requests.xml") and true
      end

      def log_requests
        response = get("#{url_prefix}/log_requests.xml")
        extract_log_requests_xml(response.body)
      end

      private

      def url_prefix
        if self.is_a? BackendClient::Application # that class loads this module as well
          ""
        else
          "/services/#{service_id}"
        end
      end

      def extract_log_requests_xml(xml_body)

        doc = Nokogiri::XML(xml_body)

        result = []
        v = doc.search('log_request')

        if v.size>0
          v.each do |item|
            h = {}
            item.search("*").each do |tuple|
              h[tuple.name] = tuple.content
            end
            h["timestamp"] = parse_timestamp(h["timestamp"])

            result << h.symbolize_keys
          end
        end

        result
      end
    end
  end
end
