class Employee::Legacy::Classrooms::StudentHabitsController < Employee::Controller
  def index
    render_success :ok, json: student_habits.map { |c| student_habit_props(c) }
  end

  def show
    render_success :ok, json: classroom.students
      .where(grade: student_habit.grade)
      .order(:last_name, :first_name)
      .map { |student|
        student_habit_value_props(student, find_or_build_student_habit_value(student.id))
      }
  end

  def batch_update
    data = []
    params[:params].each do |param|
      value = find_or_build_student_habit_value(param['student_id'])
      value.assign_attributes(value_params(param))
      data << value
    end

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

  private
    def classrooms
      current_employee.classrooms.preload(:students)
    end

    def classroom
      @classroom ||= classrooms.find_by(id: params[:classroom_id])
    end

    def student_habits
      @student_habits ||= current_school.student_habits
        .eager_load(:student_habit_group)
        .where(grade: classroom.students.pluck(:grade))
        .order('grade DESC', 'StudentHabitGroups.Name', :sequence)
    end

    def student_habit
      @student_habit ||= current_school.student_habits
        .preload(:student_habit_values)
        .find_by(id: params[:id])
    end

    def student_habit_values
      @student_habit_values ||= student_habit.student_habit_values.index_by(&:student_id)
    end

    def find_or_build_student_habit_value(student_id)
      student_habit_values[student_id] ||
        student_habit.student_habit_values.build(student_id: student_id, school: current_school)
    end

    def value_params(param)
      param.permit(:q1, :q2, :q3, :q4)
    end

    def student_habit_props(student_habit)
      {}.tap do |props|
        props[:id] = student_habit.id
        props[:name] = student_habit.name
        props[:group] = student_habit.student_habit_group&.name
        props[:grade] = student_habit.grade
      end
    end

    def student_habit_value_props(student, value)
      {}.tap do |props|
        props[:id] = student.id
        props[:student_id] = student.id
        props[:name] = student.full_name(:reverse)
        props[:q1] = value.q1
        props[:q2] = value.q2
        props[:q3] = value.q3
        props[:q4] = value.q4
      end
    end
end
