require 'db/mongo/models/statistic'
require_relative "request_handler"

module Devops
  module API3
    module Handler
      class Statistic < RequestHandler

        # supported options:
        #   user
        #   response_code (format: 200)
        #   method
        #   path
        #   path_contains
        #   date_from (format: timestamp)
        #   date_till (format: timestamp)
        #   limit: default 20. Zero value is equal to no limit.
        #   sort_field: default 'created_at'. Could also be in [user, path, method, body, response_code, created_at].
        #   sort_order: default 'asc'. Could also be 'desc'
        def statistic
          filters = @request.params
          limit =extract_limit_params_for_searching(20)
          sort = extract_sort_params_for_searching
          query = {}
          %w(user method path).each do |key|
            val = filters[key]
            query[key] = val if val
          end

          query["response_code"] = filters["response_code"].to_i if filters["response_code"]
          query["path"] = Regexp.new(filters["path_contains"], 'i') if filters["path_contains"]

          fill_date_params_for_searching(query)

          Devops::Model::Statistic.where(query).sort(sort).limit(limit)
        end

      end
    end
  end
end

