class Admins::IssuesRankController < Admins::BaseController
  before_action :require_admin

  def index 
    @statistics = DailyProjectStatistic.where('date >= ? AND date <= ?', begin_date, end_date)
    @statistics = @statistics.group(:project_id).joins(:project).select("project_id,
                                                                         sum(issues) as issues,
                                                                         sum(closed_issues) as closed_issues,
                                                                         projects.issues_count as issues_count")
    @statistics = @statistics.order("#{sort_by} #{sort_direction}").limit(50)
  end

  private 
  def begin_date 
    params.fetch(:begin_date, (Date.yesterday-7.days).to_s)
  end

  def end_date 
    params.fetch(:end_date, Date.yesterday.to_s)
  end

  def sort_by
    DailyProjectStatistic.column_names.include?(params.fetch(:sort_by, "issues")) ? params.fetch(:sort_by, "issues") : "issues"
  end

  def sort_direction
    %w(desc asc).include?(params.fetch(:sort_direction, "desc")) ? params.fetch(:sort_direction, "desc") : "desc"
  end

end