class EndExerciseCalculateJob < ApplicationJob

  include ExercisesHelper
  include GitHelper

  queue_as :default

  def perform(ex_user_ids,exercise_id,end_time,work_time,commit_method)
    exercise = Exercise.find_by(id: exercise_id)
    return if exercise.blank?
    exercise_users = ExerciseUser.where(id: ex_user_ids)
    exercise_users.each do |user|
      if user.none_commit?
        end_at = work_time ? end_time : Time.at(user.start_at + exercise.time * 60)

        calculate_result = calculate_student_score(exercise,user,end_time.to_time)
        objective_score = calculate_result[:total_score]
        reviewed = calculate_result[:reviewed]
        subjective_reviewed = calculate_result[:subjective_reviewed]

        user_sub_score = user.subjective_score
        subjective_score = user_sub_score < 0.0 ? 0.0 : user_sub_score
        total_score = objective_score + subjective_score
        if exercise.exercise_answers.where(user_id: user.user_id).blank? && exercise.exercise_shixun_answers.where(user_id: user.user_id).blank?
          commit_status = "commit_with_no_answer"
        else
          commit_status = "commited"
        end
        commit_option = {
          :status => 1,
          :commit_status => commit_status,
          :end_at => end_at,
          :objective_score => objective_score,
          :score => total_score,
          :subjective_score => user_sub_score,
          :commit_method => user&.commit_method.to_i > 0 ? user&.commit_method.to_i : commit_method,
          :reviewed => reviewed,
          :subjective_reviewed => subjective_reviewed
        }
        user.update_attributes(commit_option)
      end
    end
  end

end
