require "json"
require 'sinatra/base'
require "sinatra/json"
require "db/mongo/models/statistic"

module Devops
  module API3
    module Helpers

      include Sinatra::JSON

      def create_response msg, obj=nil, rstatus=200
        logger.info(msg)
        status rstatus
        obj = {} if obj.nil?
        obj[:message] = msg
        json(obj)
      end

      def halt_response msg, rstatus=400
        obj = {:message => msg}
        halt(rstatus, json(obj))
      end

      def check_provider provider
        list = ::Provider.providers
        halt_response("Invalid provider '#{provider}', available providers: '#{list.join("', '")}'", 400) unless list.include?(provider)
      end

      def check_provider_account provider, account
        halt_response("Provider acount '#{account}' not found", 400) if ::Provider.get_connector(provider, account).nil?
      end

      def check_policy policy
        return unless policy
        user = request.env['USER']
        user.check_policy(policy)
      end

      # Save information about requests with methods POST, PUT, DELETE
      def insert_statistic msg=nil
        unless request.get?
          return if response.status == 401 and request.env['REMOTE_USER'].nil?
          # parse body
          request.body.rewind
          raw_body = request.body.read
          body = begin
            ::JSON.parse(raw_body)
          rescue ::JSON::ParserError
            raw_body
          end

          Devops::Model::Statistic.create({
            user: request.env['REMOTE_USER'],
            path: request.path,
            method: request.request_method,
            body: body,
            response_code: response.status
          })
        end
      end

    end
  end
end

