class Admin::LogRequestsController < FrontendController
  include ThreeScale::Search::Helpers
  include CubertLogsVisibility

  before_action :authorize_log_requests

  before_action :authorize_stats
  before_action :authorize_applications

  before_action :find_service

  activate_menu :monitoring, :analytics
  sublayout :stats

  def index
    # Demeter's law!
    if provider_can_use_cubert_request_logs?
      logs_service  = CubertRequestLogsService.new(@service.cubert_info)
      @search       = ThreeScale::RequestLogsSearch.new(search_params)
      @log_requests = logs_service.get_list(@search.to_hash, pagination_params.merge(sort: sort_params))

      respond_to do |format|
        format.html { render action: 'cubert_logs' }
        format.json do
          pagination = { total: @log_requests.total_pages}.merge(pagination_params)
          render json: {logs: @log_requests, pagination: pagination}
        end
      end

    else
      @log_requests = @service.backend_object.log_requests

      @appid2app = {}

      @log_requests.each do |req|
        @appid2app[req[:app_id]] ||= @service.cinstances.find_by_application_id(req[:app_id])
      end
    end
  end

  def purge
    # Demeter's law!
    @service.backend_object.delete_all_log_requests

    respond_to do |format|
      format.html do
        flash[:notice] = 'All requests logs were purged.'
        redirect_to(admin_service_log_requests_url)
      end

      format.js
    end
  end

  protected

  def authorize_log_requests
    authorize! :see, :log_requests
  end

  def authorize_stats
    authorize! :manage, :monitoring
  end

  def authorize_applications
    authorize! :manage, :applications
  end

  def find_service
    @service ||= current_account.accessible_services.find(params[:service_id])
  end

  def search_params
    params.fetch(:search, {}).permit(:code, :application_id, { :timestamp => [:$lt, :$lte, :$gt, :$gte]}).symbolize_keys
  end

  def sort_params
    sort_column ? { sort_column => sort_direction } : { "timestamp" => "desc" }
  end

end
