class Admin::Course::ClassroomsController < Admin::Course::Controller
  def index
    data = classrooms
      .by_type(params[:type])
      .by_department(params[:department_ids])
      .by_semesters(current_school, params[:semesters])
      .by_id(params[:ids])
      .includes(:primary_teacher, :school_state_classroom)
      .decorate
    render_success :ok, json: data.map { |c| props(c) }
  end

  def batch_update
    ids = params[:data].map { |i| i[:id] }
    data = classrooms.where(id: ids)
    data.each do |classroom|
      param = params[:data].find { |i| i[:id] == classroom.id }
      classroom.assign_attributes(classroom_params(param))
    end

    if transactional_save(data)
      render_success :ok, message: "#{data.length} Classrooms updated."
    else
      render_error :unprocessable_entity
    end
  end

  private
    def classrooms
      @classrooms ||= current_school.classrooms.where.not(type: [:sports_team, :general])
    end

    def room
      @room ||= current_school.facility_rooms.find_by(id: params[:room_id])
    end

    def classroom_params(param)
      param.permit(
        :facility_id,
        :classroom_position_type_id,
        :department_id,
        :location_id
      )
    end

    def props(classroom)
      {
        id: classroom.id,
        name: classroom.name,
        section: classroom.section,
        primary_teacher: classroom.primary_teacher_full_name(:reverse),
        facility_id: classroom.facility_id&.zero? ? nil : classroom.facility_id,
        classroom_position_type_id: classroom.classroom_position_type_id,
        term: classroom.semester,
        type: classroom.type,
        location_id: classroom.location_id,
        department_id: classroom.department_id? ? classroom.department_id : nil,
        state_classroom: classroom.school_state_classroom.present?
      }
    end
end
