<?php
namespace local_treestudyplan\task;
require_once($CFG->dirroot.'/course/externallib.php');

class deepcopy extends \core\task\adhoc_task  {
    
    public const TABLE = "local_treestudyplan_item";
    private $id;

    public function __construct(){
    }

    public static function create($studyplan_id,$params){
        global $USER, $DB;

        $recordid = $DB->insert_record(self::TABLE, [
            'studyplan_id' => $studyplan_id,
            'status' => 'pending',
            'completion' => 0,
            'parameters' => \json_encode($params),
        ]);

        $task = new self();
        $task->set_custom_data((object)[ // cast to object to avoid confusion below (data encoded as JSON which always returns object on dictionary array)
            'recordid' => $recordid,
        ]);
        $task->set_userid($USER->id);
        return $task;
    }

    /**
     * Return the task's name as shown in admin screens.
     *
     * @return string
     */
    public function get_name() {
        return get_string('task_process_request', 'report_downloadall');
    }
 
    protected function setStatus($status,$completion){
        global $DB;
        if(!empty($this->id)){
            $DB->update_record(self::TABLE, ['id' => $this->id,"status"=>$status,"completion" => $completion]);
        }
    }

    public static function findStatus($studyplan_id){
        global $DB;
        $records = $DB->get_records(self::TABLE,['studyplan_id' => $studyplan_id]);
        $list = [];


        return $list;
    }


    /**
     * Execute the task.
     */
    public function execute() {
        global $DB;
        $data = $this->get_custom_data(); // returns array data as object, because JSON
        $recordid = $data->recordid;
        $this->id = $recordid;
        $record = $DB->get_record(self::TABLe,['id' => $recordid]);
        $params = \json_decode();
        
        $this->setStatus('copying',0);

        // gather the study items that need to be converted
        $studyitems = [];
        $studyplan = studyplan::findById($record->studyplan_id);
        foreach(studyline::find_studyplan_children($studyplan) as $line){
            foreach(studyitem::find_studyline_children($line) as $item){
                if($item->type() == studyitem::COURSE && $item->isValid()){
                    // queue this studyitem and related study line (for extra info)
                    $studyitems[] = [$item,$line];
                }
            }
        }

        // Make sure we can calculate progress
        $count = count($studyitems);

        for($i=0;$i<$count;$i++){
            $progress = 100.0 * (floatval($i) / floatval($count));
            $this->setStatus('copying',$progress);
            [$old, $line] = $studyitems[$i];
            $old_ci = $old->getcourseinfo();
            $old_course = $old_ci->course();

            // perform a copy of the course
            /**
             * Duplicate a course
             *
             * @param int $courseid
             * @param string $fullname Duplicated course fullname
             * @param string $shortname Duplicated course shortname
             * @param int $categoryid Duplicated course parent category id
             * @param int $visible Duplicated course availability
             * @param array $options List of backup options
             * @return array New course info
             * @since Moodle 2.3
             */
            // public static function  duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array());

            if(!array_key_exists($old_course->id))
            {
                $new_fullname = $old_course->fullname;
                $new_shortname = $old_course->shortname;
                $new_categoryid = $old_course->category; // We likely don't want this in the same cetegory, but in a new one for the next school year
                // TODO: select new category, and optionally include 

                // TODO: generate new shortname and verify it is unique

                [$new_course_id,] = \core_course_external::duplicate_course($old_course->id,$new_fullname,$new_shortname,$new_categoryid,true,[
                    'enrolments' => 0,
                ]);

                $duplicationmap[$old_course->id] = $new_course_id;
            }
            else {
                $new_course_id = $duplicationmap[$old_course->id];
            }

            // retrieve the course
            $new_course = \get_course($new_course_id);

            // now, update the timing of the course, based on the provided parameters
            // TODO: Make sure that the timing of courses included in multiple slots, is updated to match the start and end of alle those slots.

            
        }
        $this->setStatus('done',$progress);

    }
}