#coding=utf-8

namespace :exercise_publish do
  desc "publish exercise and end exercise"
  task :publish => :environment do
    exercises = Exercise.where("publish_time is not null and exercise_status = 1 and publish_time <=?",Time.now)
    exercises.each do |exercise|
      exercise.update_column('exercise_status', 2)
      course = exercise.course
      course.members.each do |m|
        exercise.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => course.id, :viewed => false, :status => 2)
      end
    end
  end

  task :end => :environment do
    include ExerciseHelper
    exercises = Exercise.where("end_time <=? and exercise_status = 2",Time.now)
    exercises.each do |exercise|
      course = exercise.course
      exercise.update_column('exercise_status', 3)
      course.student.each do |student|
        if ExerciseUser.where("user_id = ? && exercise_id = ?",student.student_id,exercise.id).empty?
          ExerciseUser.create(:user_id => student.student_id, :exercise_id => exercise.id, :start_at => exercise.end_time, :status => true,:score=>0)
        end
=begin
        s_score = calculate_student_score(exercise, student.student)
        exercise_user = ExerciseUser.where("user_id =? and exercise_id=?", student.student_id, exercise.id).first
        exercise_user.update_attributes(:score => s_score)
=end
      end
    end
  end
end
