<?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_multiple_structure;
use core_external\external_single_structure;
use core_external\external_value;
use local_gamibot_manager\gamibot_manager_utils;

/**
 * External function to provide general information.
 *
 * @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 get_user_gami_stats extends external_api {
    /**
     * Describes the parameters.
     *
     * @return external_function_parameters
     */
    public static function execute_parameters(): external_function_parameters {
        return new external_function_parameters([
            'component' => new external_value(PARAM_ALPHANUMEXT, 'The component name', VALUE_REQUIRED),
            'contextid' => new external_value(PARAM_INT,
                'The id of the current context',
                VALUE_DEFAULT,
                0),
            'options' => new external_value(PARAM_RAW, 'Options object JSON stringified', VALUE_DEFAULT, ''),
        ]);
    }

    /**
     * Retrieve the general AI info object.
     *
     * @param string $component the component name.
     * @param int $contextid The context in which the gami stats should be retrieved, should be a course context.
     * @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(string $component, int $contextid, string $options): array {
        global $USER;

        [
                'component' => $component,
                'contextid' => $contextid,
                'options' => $options
        ] = self::validate_parameters(self::execute_parameters(),
                [
                        'component' => $component,
                        'contextid' => $contextid,
                        'options' => $options
                ]
        );
        $context = $contextid === 0 ? \context_system::instance() : \context::instance_by_id($contextid);
        self::validate_context($context);
        require_capability('local/gamibot_manager:use', $context);

        // 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 ' . $contextid . ' is not a course context.'];
            return ['code' => 400, 'string' => 'error', 'result' => json_encode($error)];
        }
        $courseid = $parentcoursecontext->instanceid;

        try {
            $client = gamibot_manager_utils::get_gami_api_client();
            $result = $client->get_user_course_stats(strval($USER->id), strval($courseid));
            $return = ['code' => 200, 'string' => 'ok', 'result' => json_encode($result)];
        } catch (\Exception $e) {
            $error = ['message' => $e->getMessage()];
            $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'),
            ]
        );
    }
}
