/**
 * Onlinejudge_task_judged event handler
 *
 * Update the grade and etc.
 *
 * @param object task
 */
function onlinejudge_task_judged($task)
{
    global $DB;
    $sql = 'SELECT s.*
        FROM {assignment_submissions} s LEFT JOIN {assignment_oj_submissions} o
        ON s.id = o.submission
        WHERE o.task = ?';
    if (!($submission = $DB->get_record_sql($sql, array($task->id)))) {
        return true;
        // true means the event is processed. false will cause retry
    }
    $cm = get_coursemodule_from_instance('assignment', $submission->assignment);
    $ass = new assignment_onlinejudge($cm->id, NULL, $cm);
    $sql = 'SELECT s.*, t.subgrade
        FROM {assignment_oj_submissions} s LEFT JOIN {assignment_oj_testcases} t
        ON s.testcase = t.id
        WHERE s.submission = ? AND s.latest = 1';
    if (!($onlinejudges = $DB->get_records_sql($sql, array($submission->id)))) {
        return true;
        // true means the event is processed. false will cause retry
    }
    $finalgrade = 0;
    foreach ($onlinejudges as $oj) {
        if ($task = onlinejudge_get_task($oj->task)) {
            $task->grade = $ass->grade_marker($task->status, $oj->subgrade);
            if ($task->grade == -1) {
                // Not all testcases are judged, or judge engines internal error
                // In the case of internal error, keep old grade is reasonable
                // since most of ie is caused by system
                return true;
            }
            $finalgrade += $task->grade;
        }
    }
    $submission->grade = $finalgrade;
    $submission->timemarked = time();
    $submission->mailed = 1;
    // do not notify student by mail
    $submission->teacher = get_admin()->id;
    $DB->update_record('assignment_submissions', $submission);
    $ass->update_grade($submission);
    return true;
}