using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

public static class MoodleApi
{
    private static string moodleToken = "c7d012a8c704fae756c50d15468c7d61";
    private static string moodleUrl = "https://expertlab.stepsconsulting.fr/";
    private static string moodleWebServiceUrl = $"{moodleUrl}webservice/rest/server.php";
    public static string userId = "17"; //"6553";

    public static IEnumerator GetCompletionStatus(int courseId, CourseDescriptor descriptor)
    {
        string url =
            $"{moodleWebServiceUrl}?wstoken={moodleToken}&wsfunction=core_completion_get_course_completion_status&moodlewsrestformat=json&courseid={courseId}&userid={userId}";
        //  string url = $"{moodleWebServiceUrl}?wstoken={moodleToken}&wsfunction=core_completion_get_activities_completion_status&moodlewsrestformat=json&courseid={courseId}&userid={userId}";
        //  string url = string.Format("{0}?wstoken={1}&wsfunction=gradereport_user_get_grade_items&moodlewsrestformat=json&courseid={2}&userid={3}", moodleUrl, moodleToken, courseId, userId);
        UnityWebRequest www = UnityWebRequest.Get(url);
        yield return www.SendWebRequest();

        if (www.result == UnityWebRequest.Result.Success)
        {
            descriptor.CompletionFromJson(www.downloadHandler.text);
            Debug.Log("EE " + www.downloadHandler.text);
        }
        else
        {
            Debug.LogError("Error: " + www.error);
        }
    }

    public static string GetCourseUrl(int courseId)
    {
        return $"{moodleUrl}/course/view.php?id={courseId}";
    }

    public static IEnumerator GetCourseInfoCoroutine(int courseId, CourseDescriptor descriptor)
    {
        string url =
            $"{moodleWebServiceUrl}?wstoken={moodleToken}&wsfunction=core_course_get_courses&moodlewsrestformat=json&options[ids][0]={courseId}";

        UnityWebRequest www = UnityWebRequest.Get(url);
        yield return www.SendWebRequest();

        if (www.result == UnityWebRequest.Result.Success)
        {
            descriptor.FromJson(www.downloadHandler.text);
        }
        else
        {
            Debug.LogError("Error: " + www.error);
        }
    }
}