<?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 local_gamibot_manager\external;

use core_external\external_api;
use core_external\external_function_parameters;
use core_external\external_single_structure;
use core_external\external_value;
use local_gamibot_manager\gamibot_manager_utils;

/**
 * Web service to submit a quiz score to Gami API.
 *
 * @package    local_gamibot_manager
 * @copyright  Centro de Inovação Pedagógica P. Porto
 * @author     José C. Paiva
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class submit_quiz_score extends external_api {
    /**
     * Describes the parameters.
     *
     * @return external_function_parameters
     */
    public static function execute_parameters(): external_function_parameters {
        return new external_function_parameters([
                'points' => new external_value(PARAM_INT, 'The score of the quiz.', VALUE_REQUIRED),
                'total' => new external_value(PARAM_INT, 'The total number of questions in the quiz.', VALUE_REQUIRED),
                'topic' => new external_value(PARAM_INT, 'The topic of the quiz.', VALUE_DEFAULT, null),
                'component' => new external_value(PARAM_ALPHANUMEXT, 'The component name', VALUE_REQUIRED),
                'contextid' => new external_value(PARAM_INT, 'The context id of the context from which the request is being done',
                        VALUE_REQUIRED),
                'options' => new external_value(PARAM_RAW, 'Options object JSON stringified', VALUE_DEFAULT, ''),
        ]);
    }

    /**
     * Execute the service.
     *
     * @param int $points the score of the quiz
     * @param int $total the total number of questions in the quiz
     * @param int|null $topic the topic of the quiz
     * @param string $component the component name
     * @param int $contextid the context id of the context from which the request is being done
     * @param string $options additional options which should be passed to the request
     * @return array associative array containing the result of the request
     */
    public static function execute(int $points, int $total, ?int $topic, string $component, int $contextid, string $options): array {
        [
                'points' => $points,
                'total' => $total,
                'topic' => $topic,
                'component' => $component,
                'contextid' => $contextid,
                'options' => $options,
        ] = self::validate_parameters(self::execute_parameters(), [
                'points' => $points,
                'total' => $total,
                'topic' => $topic,
                'component' => $component,
                'contextid' => $contextid,
                'options' => $options,
        ]);
        if (!empty($options)) {
            $options = json_decode($options, true);
        }
        $context = $contextid === 0 ? \context_system::instance() : \context::instance_by_id($contextid);
        self::validate_context($context);
        // We do not check the 'local/gamibot_manager:use' capability here, because this is being done inside manager::perform_request.

        // Get the course context if we are in a course context, else return an error.
        $parentcoursecontext = gamibot_manager_utils::find_closest_parent_course_context($context);
        if (is_null($parentcoursecontext)) {
            $error = ['message' => 'The context is not a course context.'];
            if (debugging()) {
                $error['debuginfo'] = 'The context ' . $contextid . ' is not a course context.';
            }
            return ['code' => 400, 'string' => 'error', 'result' => json_encode($error)];
        }
        $courseid = $parentcoursecontext->instanceid;

        try {
            $aimanager = new \local_gamibot_manager\manager('quiz');

            $aimanager->send_quiz_score_to_gami_api(
                $courseid,
                $options['itemid'],
                $points,
                $total,
                $topic
            );

            $return = ['code' => 200, 'string' => 'ok', 'result' => ''];
        } catch (\Exception $e) {
            $error = ['message' => $e->getMessage()];
            if (debugging()) {
                $error['debuginfo'] = $e->getTraceAsString();
            }
            $return = ['code' => 500, 'string' => 'error', 'result' => json_encode($error)];
        }

        return $return;
    }

    /**
     * Describes the return structure of the service.
     *
     * @return external_single_structure the return structure
     */
    public static function execute_returns(): external_single_structure {
        return new external_single_structure(
                [
                        'code' => new external_value(PARAM_INT, 'Return code of process.'),
                        'string' => new external_value(PARAM_TEXT, 'Return string of process.'),
                        'result' => new external_value(PARAM_RAW, 'The query result'),
                ],
                'Result of a query'
        );
    }
}
