<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * @package    block_ned_teacher_tools
 * @subpackage NED
 * @copyright  2023 NED {@link http://ned.ca}
 * @author     NED {@link http://ned.ca}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @see        cta_update_task
 */

namespace block_ned_teacher_tools\task;

use block_ned_teacher_tools\shared_lib as SH;
use block_ned_teacher_tools\cta_tracker;

defined('MOODLE_INTERNAL') || die();
require_once(__DIR__. '/../../lib.php');

/**
 * Class cta_update_task
 *
 * @package block_ned_teacher_tools\task
 */
class cta_update_task extends \core\task\scheduled_task {
    use \local_ned_controller\task\base_task;

    /**
     * Do the job.
     *
     * @param array|object|static|null $task_or_data
     *
     * @return void
     */
    static public function do_job($task_or_data=[]) {
        $courses = SH::get_all_courses();
        $c = count($courses);
        static::print("There are $c courses to update");

        foreach ($courses as $course){
            try {
                if (cta_tracker::update_cta_graders_by_course($course, true)){
                    static::print("Course $course->id \t- checked");
                } else {
                    static::print("Course $course->id \t- pass");
                }
            } catch (\Exception $e){
                $e_info = get_exception_info($e);
                $logerrmsg = "!!! Error !!! (course $course->id)" .
                    "\nException handler: ".$e_info->message.
                    "\nDebug: ".$e_info->debuginfo."\n".format_backtrace($e_info->backtrace, true);
                static::print($logerrmsg, true);
                continue;
            }
        }
    }
}
