/**
 * SPDX-FileCopyrightText: 2024-2026 Sebastien Jodogne, EPL UCLouvain, Belgium
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

/**
 * Orthanc for Education
 * Copyright (C) 2024-2026 Sebastien Jodogne, EPL UCLouvain, Belgium
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * This program 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
 * Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 **/


#include "EducationPluginsApi.h"

#include "HttpToolbox.h"
#include "ProjectPermissionContext.h"

#include "../Resources/Orthanc/Plugins/OrthancPluginCppWrapper.h"


void GetProjectInfo(OrthancPluginRestOutput* output,
                    const char* url,
                    const OrthancPluginHttpRequest* request)
{
  if (request->authenticationPayloadSize != 0)
  {
    throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);  // Should never happen
  }
  else if (request->method != OrthancPluginHttpMethod_Get)
  {
    OrthancPluginSendMethodNotAllowed(OrthancPlugins::GetGlobalContext(), output, "GET");
  }
  else
  {
    std::map<std::string, std::string> args;
    HttpToolbox::RetrieveGetArguments(args, request);

    std::map<std::string, std::string>::const_iterator found = args.find("id");
    if (found == args.end())
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_NetworkProtocol);
    }

    Json::Value answer;

    {
      DocumentOrientedDatabase::Reader reader(ProjectPermissionContext::GetProjects());
      const Project* project = reader.LookupDocument<Project>(found->second);

      if (project == NULL)
      {
        throw Orthanc::OrthancException(Orthanc::ErrorCode_UnknownResource, "Unknown project: \"" + found->second + "\"");
      }
      else
      {
        answer["name"] = project->GetName();
        answer["description"] = project->GetDescription();
        answer["policy"] = EnumerationToString(project->GetPolicy());

        /**
         * It makes no sense to report "project->GetInstructors()" and
         * "project->GetLearners()" here, as they might be pointless
         * (for instance, if using LTI-based authentication).
         **/
      }
    }

    HttpToolbox::AnswerJson(output, answer);
  }
}


void RegisterEducationPluginsApiRoutes()
{
  // All the routes below must be branched under "/education/api-plugins/",
  // which is protected by "DoAuthorization()"

  OrthancPlugins::RegisterRestCallback<GetProjectInfo>("/education/api-plugins/project", true);
}
