require 'date'
require 'exceptions/parser_error'

module Devops
  module API3
    module Handler
      class RequestHandler

        DATE_FORMAT = "%Y-%m-%d"

        class << self
          def set_parser parser
            define_method("parser") do
              @request_parser ||= parser.new(@request)
            end
          end
        end

        def initialize request
          @request = request
        end

        # supported options:
        #   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 extract_sort_params_for_searching
          filters = @request.params
          sort = {}
          sort[filters["sort_field"] || 'created_at'] = (filters["sort_order"] || 'asc') == 'asc' ? 1 : -1
          sort
        end

        # supported options:
        #   date_from_l (format: unixtime)
        #   date_til_ll (format: unxitime)
        #   date_from (format: YYYY-MM-DD)
        #   date_till (format: YYYY-MM-DD)
        def fill_date_params_for_searching search_query
          filters = @request.params
          from = begin
            parse_date(filters["date_from"], filters["date_from_l"])
          rescue ArgumentError
            raise Devops::Exception::ParserError.new("Invalid parameter 'date_from' or 'date_from_l'")
          end
          till = begin
            parse_date(filters["date_till"], filters["date_till_l"])
          rescue ArgumentError
            raise Devops::Exception::ParserError.new("Invalid parameter 'date_till' or 'date_till_l'")
          end
          from = {'$gte' => from.to_i} if from
          till = {'$lt'  => till.to_i} if till
          if !from.nil? and !till.nil?
            search_query["created_at"] = from.merge(till)#{'$and' => [from, till]}
          elsif !from.nil?
            search_query["created_at"] = from
          elsif !till.nil?
            search_query["created_at"] = till
          end
        end

        def extract_limit_params_for_searching _default=20
          filters = @request.params
          unless filters["limit"].nil?
            begin
              buf = Integer(filters["limit"])
              return buf if buf >= 0
            rescue ArgumentError
            end
          end
          _default
        end

        private
        def parse_date str, unix
          if str
            Date.strptime(str, DATE_FORMAT)
          elsif unix
            Integer(unix)
          else
            nil
          end
        end

        def owner_from_request
          @request.env['REMOTE_USER']
        end
      end
    end
  end
end
