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

/**
 * This file contains the backend webservice contact functionality for the DTA plugin
 *
 * @package    assignsubmission_dta
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @copyright Gero Lueckemeyer and student project teams
 */

/**
 * backend webservice contact utility class
 *
 * @package assignsubmission_dta
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @copyright Gero Lueckemeyer and student project teams
 */
class DtaBackendUtils {

    /**
     * Returns the base url of the backend webservice as configured in the administration settings.
     * @return string backend host base url
     */
    private static function getbackendbaseurl(): string {
        $backendaddress = get_config(assign_submission_dta::COMPONENT_NAME, "backendHost");

        if (empty($backendaddress)) {
            \core\notification::error(get_string("backendHost_not_set", assign_submission_dta::COMPONENT_NAME));
        }

        return $backendaddress;
    }

    /**
     * Sends the configuration textfile uploaded by prof to the backend.
     *
     * @param stdClass $assignment assignment this test-config belongs to
     * @param stdClass $file uploaded test-config
     * @return bool true if no error occurred
     */
    public static function sendtestconfigtobackend($assignment, $file): bool {
        $backendaddress = self::getbackendbaseurl();
        if (empty($backendaddress)) {
            return true;
        }

        // Set endpoint for test upload.
        $url = $backendaddress . "/v1/unittest";

        // Prepare params.
        $params = [
            "unitTestFile" => $file,
            "assignmentId" => $assignment->get_instance()->id,
        ];

        // If request returned null, return false to indicate failure.
        if (is_null(self::post($url, $params))) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Sends submission config or archive to backend to be tested.
     *
     * @param stdClass $assignment assignment for the submission
     * @param int $submissionid submissionid of the current file
     * @param stdClass $file submission config file or archive with submission
     * @return string json string with testresults or null on error
     */
    public static function sendsubmissiontobackend($assignment, $submissionid, $file): ?string {
        $backendaddress = self::getbackendbaseurl();
        if (empty($backendaddress)) {
            return true;
        }

        // Set endpoint for test upload.
        $url = $backendaddress . "/v1/task/" . $submissionid;

        // Prepare params.
        $params = [
            "taskFile" => $file,
            "assignmentId" => $assignment->get_instance()->id,
        ];

        return self::post($url, $params);
    }

    /**
     * Posts the given params to the given url and returns the response as a string.
     * @param string $url full url to request to
     * @param array $params parameters for http-request
     *
     * @return string received body on success or null on error
     */
    private static function post($url, $params): ?string {
        if (!isset($url) || !isset($params)) {
            return false;
        }

        $options = ["CURLOPT_RETURNTRANSFER" => true];

        $curl = new curl();
        $response = $curl->post($url, $params, $options);

        // Check state of request, if response code is a 2xx return the answer.
        $info = $curl->get_info();
        if ($info["http_code"] >= 200 && $info["http_code"] < 300) {
            return $response;
        }

        // Something went wrong, return null and give an error message.
        debugging(assign_submission_dta::COMPONENT_NAME . ": Post file to server was not successful: http_code=" .
        $info["http_code"]);

        if ($info['http_code'] >= 400 && $info['http_code'] < 500) {
            \core\notification::error(get_string("http_client_error_msg", assign_submission_dta::COMPONENT_NAME));
            return null;
        } else if ($info['http_code'] >= 500 && $info['http_code'] < 600) {
            \core\notification::error(get_string("http_server_error_msg", assign_submission_dta::COMPONENT_NAME));
            return null;
        } else {
            \core\notification::error(get_string("http_unknown_error_msg", assign_submission_dta::COMPONENT_NAME) .
            $info["http_code"] . $response);
            return null;
        }
    }

}