class Admin::StateReporting::SchoolYears::SchoolDaysController < Admin::Administration::Controller
  include DateRangeHelper

  def index
    data = school_days.with_date_range(date_range(params[:dates])).map { |d| school_day_props(d) }
    render_success :ok, json: data
  end

  def batch_update
    days = school_days.where(id: params[:ids]).map do |day|
      day.assign_attributes(school_day_params)
      day
    end

    if transactional_save(days)
      render_success :ok, message: "#{days.count} days updated."
    else
      render_error :unprocessable_entity, errors: multi_errors(days)
    end
  end

  private
    def school_year
      @school_year ||= current_school.school_years.find_by(id: params[:school_year_id])
    end

    def school_days
      school_year.school_days.includes(:day_descriptor)
    end

    def school_day_params
      params.permit(:hours, :half_day).merge(associations)
    end

    def associations
      {}.tap do |prop|
        if params[:day_descriptor_id]
          prop[:day_descriptor] = EdFi::Descriptor.find_by(id: params[:day_descriptor_id])
        end
      end
    end

    def school_day_props(day)
      {
        id: day.id,
        date: day.date,
        quarter: day.quarter,
        half_day: day.half_day?,
        hours: day.hours,
        day_descriptor_id: day.day_descriptor_id,
        day_descriptor_name: day.decorate.day_descriptor_name
      }
    end
end
