class HomeworkEvaluationCommentAssginJob < ApplicationJob
  queue_as :default

  def get_assigned_homeworks(student_works, n, index)
    student_works += student_works
    student_works[index + 1..index + n]
  end

  def perform(homework_common_id)
    homework_common = HomeworkCommon.find_by(id: homework_common_id)
    return if homework_common.blank?
    homework_detail_manual = homework_common.homework_detail_manual

    if homework_common.homework_type == "group"
      student_works = homework_common.student_works.where("work_status != 0").group(:group_id)
      student_work_projects = homework_common.student_works.where("work_status != 0").shuffle
      student_work_projects.each do |pro_work|
        n = homework_detail_manual.evaluation_num
        n = (n < student_works.length && n != -1) ? n : student_works.length - 1
        work_index = -1
        student_works.each_with_index do |stu_work, stu_index|
          if stu_work.group_id.to_i == pro_work.group_id.to_i
            work_index = stu_index
          end
        end
        assigned_homeworks = get_assigned_homeworks(student_works, n, work_index)
        assigned_homeworks.each do |h|
          student_works_evaluation_distributions = StudentWorksEvaluationDistribution.new(user_id: pro_work.user_id, student_work_id: h.id)
          student_works_evaluation_distributions.save
        end
      end

    else
      student_works = homework_common.student_works.has_committed
      student_works = student_works.shuffle
      student_works.each_with_index do |work, index|
        user = work.user
        n = homework_detail_manual.evaluation_num
        n = (n < student_works.size && n != -1) ? n : student_works.size - 1
        assigned_homeworks = get_assigned_homeworks(student_works, n, index)
        assigned_homeworks.each do |h|
          student_works_evaluation_distributions = StudentWorksEvaluationDistribution.new(user_id: user.id, student_work_id: h.id)
          student_works_evaluation_distributions.save
        end
      end
    end
  end
end
