ActiveAdmin.register JamRuby::User, :as => 'Onboarder' do

  menu :label => 'Onboarder Settings', :parent => 'JamClass'

  config.sort_order = 'created_at'
  config.batch_actions = true
  config.per_page = 100
  config.paginate = true
  config.filters = false
  config.clear_action_items!
  batch_action :destroy, false

  scope("All Onboarders", default: true) { |scope| scope.where(is_onboarder: true).order(:created_at) }

  controller do
    active_admin_config.includes.push :onboarding_users

    def update
      resource.max_onboardings = params[:jam_ruby_user][:max_onboardings]
      resource.save!
      success.json {}
    end
  end



  index do
    def last_week
      @last_week_result ||= calculate_last_week
    end

    def calculate_last_week
      start_day = Date.today.beginning_of_week(:sunday).yesterday.beginning_of_week(:sunday)
      end_day = start_day.end_of_week(:sunday)
      result = [start_day, end_day]
      result
    end

    def this_week
      @this_week_result ||= calculate_this_week
    end

    def calculate_this_week
      start_day = Date.today.beginning_of_week(:sunday)
      end_day = start_day.end_of_week(:sunday)
      result = [start_day, end_day]
      result
    end

    def week_display(week)
      start_day = week[0]
      end_day = week[1]
      mmyy = start_day.strftime('%b')
      "#{mmyy} #{start_day.day}-#{end_day.day}"
    end

    def onboarding_select
      array = []
      100.times do |i|
        array.push [i.to_s, i.to_s]
      end
      array
    end
    column "Name" do |user|
      div do
        div do
          link_to user.name, user.admin_url
        end
        div do
          user.email
        end
      end
    end
    column "Max Onboardings" do |user|
      best_in_place user, :max_onboardings, as: :select, url: admin_onboarder_path(user),:collection => onboarding_select
    end
    column "Current Week #{week_display(this_week)}" do |user|
      start_date, last_date = this_week
      user.onboarding_users.where(onboarder_assigned_at: start_date..last_date).count
    end
    column "Previous Week #{week_display(last_week)}" do |user|
      start_date, last_date = last_week
      user.onboarding_users.where(onboarder_assigned_at: start_date..last_date).count
    end
    column "Current Student WIP" do |user|
      user.onboarding_users.where('onboarding_status = ? OR onboarding_status = ?', User::ONBOARDING_STATUS_ASSIGNED, User::ONBOARDING_STATUS_EMAILED).count
    end
  end


end