<?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/>.

namespace core_courseformat\external;

use core_external\external_api;
use core_external\external_function_parameters;
use core_external\external_value;

/**
 * Class for exporting a course state.
 *
 * @package    core_course
 * @copyright  2021 Ferran Recio <ferran@moodle.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since      Moodle 4.0
 */
class get_state extends external_api {

    /**
     * Webservice parameters.
     *
     * @return external_function_parameters
     */
    public static function execute_parameters(): external_function_parameters {
        return new external_function_parameters([
            'courseid' => new external_value(PARAM_INT, 'course id', VALUE_REQUIRED),
        ]);
    }

    /**
     * This method will load all course, sections and cm states needed to initialize the frontend
     * course editor module. The state data of every individual course, section and cm is
     * build using the specifics "state" output components.
     *
     * By default, the states are generated by:
     *  - core_courseformat\output\state\course
     *  - core_courseformat\output\state\section
     *  - core_courseformat\output\state\cm
     *
     * As the other main course outputs, format plugins can override those output components
     * to send more information to the frontend course editor. These extended classes should
     * be located in format_XXX\output\courseformat\state\course, format_XXX\output\courseformat\state\section
     * or format_XXX\output\courseformat\state\cm.
     *
     * @param int $courseid the course id
     * @return string Course state in JSON
     */
    public static function execute(int $courseid): string {
        global $PAGE, $CFG;

        require_once($CFG->dirroot.'/course/lib.php');

        $params = external_api::validate_parameters(self::execute_parameters(), [
            'courseid' => $courseid,
        ]);
        $courseid = $params['courseid'];

        self::validate_context(\context_course::instance($courseid));

        $courseformat = course_get_format($courseid);
        $modinfo = $courseformat->get_modinfo();

        // Get the proper renderer.
        $renderer = $courseformat->get_renderer($PAGE);

        $result = (object)[
            'course' => (object)[],
            'section' => [],
            'cm' => [],
        ];

        // Load the output class names.
        $courseclass = $courseformat->get_output_classname('state\\course');
        $sectionclass = $courseformat->get_output_classname('state\\section');
        $cmclass = $courseformat->get_output_classname('state\\cm');

        // General state.
        $coursestate = new $courseclass($courseformat);
        $result->course = $coursestate->export_for_template($renderer);

        // Sections and course modules state.
        $sections = $modinfo->get_section_info_all();
        foreach ($sections as $section) {
            if ($courseformat->is_section_visible($section)) {
                // Only return this section data if it's visible by current user on the course page.
                $sectionstate = new $sectionclass($courseformat, $section);
                $result->section[] = $sectionstate->export_for_template($renderer);
            }
        }

        foreach ($modinfo->cms as $cm) {
            if ($cm->is_visible_on_course_page()) {
                // Only return this course module data if it's visible by current user on the course page.
                $section = $sections[$cm->sectionnum];
                $cmstate = new $cmclass($courseformat, $section, $cm);
                $result->cm[] = $cmstate->export_for_template($renderer);
            }
        }

        return json_encode($result);
    }

    /**
     * Webservice returns.
     *
     * @return external_value
     */
    public static function execute_returns(): external_value {
        return new external_value(PARAM_RAW, 'Encoded course state JSON');
    }
}
