/** Removes a task. */
  @Override
  public void unAssignTask(Task task) throws WorkflowException {
    String componentId = task.getProcessInstance().getModelId();
    ComponentInst compoInst = null;

    try {
      compoInst = AdminReference.getAdminService().getComponentInst(componentId);
    } catch (AdminException e) {
      throw new WorkflowException(
          "TaskManagerImpl.unassignTask", "workflowEngine.EX_GET_COMPONENT_INST", e);
    }

    TodoBackboneAccess todoBBA = new TodoBackboneAccess();

    if (task.getUser() != null) {
      todoBBA.removeEntriesFromExternal(
          compoInst.getDomainFatherId(), componentId, getExternalId(task));
    } else {
      String role = task.getUserRoleName();
      List<User> usersInRole = task.getProcessInstance().getUsersInRole(role);
      for (User userInRole : usersInRole) {
        TaskImpl taskImpl =
            new TaskImpl(userInRole, role, task.getProcessInstance(), task.getState());
        todoBBA.removeEntriesFromExternal(
            compoInst.getDomainFatherId(),
            componentId,
            getExternalId(taskImpl, userInRole.getUserId()));
      }
    }
  }
  /**
   * Adds a new task in the user's todos. Returns the external id given by the external todo system.
   */
  @Override
  public void assignTask(Task task, User delegator) throws WorkflowException {
    String componentId = task.getProcessInstance().getModelId();
    ComponentInst compoInst = null;

    try {
      compoInst = AdminReference.getAdminService().getComponentInst(componentId);
    } catch (AdminException e) {
      throw new WorkflowException(
          "TaskManagerImpl.assignTask", "workflowEngine.EX_GET_COMPONENT_INST", e);
    }

    TodoDetail todo = new TodoDetail();
    todo.setId(task.getProcessInstance().getInstanceId());
    todo.setSpaceId(compoInst.getDomainFatherId());
    todo.setComponentId(componentId);
    todo.setName("activite : " + task.getState().getLabel(task.getUserRoleName(), "fr"));
    if (delegator != null) {
      todo.setDelegatorId(delegator.getUserId());
    } else {
      SilverTrace.error(
          "workflowEngine",
          "TaskManagerImpl.assignTask",
          "root.MSG_GEN_PARAM_VALUE",
          "Undefined delegator for new task : " + todo.getName());
    }

    TodoBackboneAccess todoBBA = new TodoBackboneAccess();
    Vector<Attendee> attendees = new Vector<Attendee>();
    if (task.getUser() != null) {
      // add todo to specified user
      attendees.add(new Attendee(task.getUser().getUserId()));
      todo.setAttendees(attendees);
      todo.setExternalId(getExternalId(task));
      todoBBA.addEntry(todo);
    } else {
      List<User> users = null;
      if (StringUtil.isDefined(task.getGroupId())) {
        // get users according to group
        users = task.getProcessInstance().getUsersInGroup(task.getGroupId());
      } else {
        // get users according to role
        users = task.getProcessInstance().getUsersInRole(task.getUserRoleName());
      }
      for (User user : users) {
        attendees.clear();
        attendees.add(new Attendee(user.getUserId()));
        todo.setAttendees(attendees);
        todo.setExternalId(getExternalId(task, user.getUserId()));
        todoBBA.addEntry(todo);
      }
    }
  }
  @Override
  protected void fillUserRoles(
      Set<SilverpeasRole> userRoles,
      AccessControlContext context,
      String userId,
      String componentId) {
    // Personal space or user tool
    if (componentId == null || getOrganisationController().isToolAvailable(componentId)) {
      userRoles.add(SilverpeasRole.admin);
      return;
    }
    if (Admin.ADMIN_COMPONENT_ID.equals(componentId)) {
      if (getOrganisationController().getUserDetail(userId).isAccessAdmin()) {
        userRoles.add(SilverpeasRole.admin);
      }
      return;
    }

    ComponentInst componentInst = getOrganisationController().getComponentInst(componentId);
    if (componentInst == null) {
      return;
    }

    if (componentInst.isPublic()
        || StringUtil.getBooleanValue(
            getOrganisationController().getComponentParameterValue(componentId, "publicFiles"))) {
      userRoles.add(SilverpeasRole.user);
      if (!CollectionUtils.containsAny(
              AccessControlOperation.PERSIST_ACTIONS, context.getOperations())
          && !context.getOperations().contains(AccessControlOperation.download)) {
        // In that case, it is not necessary to check deeper the user rights
        return;
      }
    }

    if (getOrganisationController().isComponentAvailable(componentId, userId)) {
      Set<SilverpeasRole> roles =
          SilverpeasRole.from(getOrganisationController().getUserProfiles(userId, componentId));
      // If component is available, but user has no rights -> public component
      if (roles.isEmpty()) {
        userRoles.add(SilverpeasRole.user);
      } else {
        userRoles.addAll(roles);
      }
    }
  }
  /**
   * Méthode métier du moteur d'importExport créant toutes les publications massives définies au
   * niveau du fichier d'import xml passé en paramètre au moteur d'importExport.
   *
   * @param userDetail - contient les informations sur l'utilisateur du moteur d'importExport
   * @param repositoriesType - objet mappé par castor contenant toutes les informations de création
   *     des publications du path défini
   * @return un objet ComponentReport contenant les informations de création des publications
   *     unitaires et nécéssaire au rapport détaillé
   */
  public void processImport(
      RepositoriesType repositoriesType,
      ImportSettings settings,
      ImportReportManager reportManager) {
    List<RepositoryType> listRep_Type = repositoriesType.getListRepositoryType();
    Iterator<RepositoryType> itListRep_Type = listRep_Type.iterator();
    AttachmentImportExport attachmentIE = new AttachmentImportExport();
    VersioningImportExport versioningIE = new VersioningImportExport(settings.getUser());
    PdcImportExport pdcIE = new PdcImportExport();

    while (itListRep_Type.hasNext()) {
      RepositoryType rep_Type = itListRep_Type.next();

      String componentId = rep_Type.getComponentId();
      int topicId = rep_Type.getTopicId();
      String sPath = rep_Type.getPath();

      // Création du rapport de repository
      MassiveReport massiveReport = new MassiveReport();
      reportManager.addMassiveReport(massiveReport, componentId);
      massiveReport.setRepositoryPath(sPath);

      ComponentInst componentInst =
          OrganisationControllerFactory.getOrganisationController().getComponentInst(componentId);
      if (componentInst == null) {
        // le composant n'existe pas
        massiveReport.setError(UnitReport.ERROR_NOT_EXISTS_COMPONENT);
      } else {
        reportManager.setComponentName(componentId, componentInst.getLabel());

        File path = new File(sPath);
        if (!path.isDirectory()) {
          // La variable path ne peut contenir qu'un dossier
          massiveReport.setError(UnitReport.ERROR_NOT_EXISTS_OR_INACCESSIBLE_DIRECTORY);
        } else {
          GEDImportExport gedIE =
              ImportExportFactory.createGEDImportExport(settings.getUser(), componentId);

          Iterator<File> itListcontenuPath = getPathContent(path);
          while (itListcontenuPath.hasNext()) {
            File file = itListcontenuPath.next();
            if (file.isFile()) {
              settings.setFolderId(String.valueOf(topicId));
              importFile(file, reportManager, massiveReport, gedIE, pdcIE, settings);
            } else if (file.isDirectory()) {
              switch (rep_Type.getMassiveTypeInt()) {
                case RepositoryType.NO_RECURSIVE:
                  // on ne fait rien
                  break;
                case RepositoryType.RECURSIVE_NOREPLICATE:
                  // traitement récursif spécifique
                  settings.setPathToImport(file.getAbsolutePath());
                  processImportRecursiveNoReplicate(
                      reportManager,
                      massiveReport,
                      gedIE,
                      attachmentIE,
                      versioningIE,
                      pdcIE,
                      settings);
                  break;
                case RepositoryType.RECURSIVE_REPLICATE:
                  try {
                    NodeDetail nodeDetail = gedIE.addSubTopicToTopic(file, topicId, massiveReport);
                    // Traitement récursif spécifique
                    settings.setPathToImport(file.getAbsolutePath());
                    settings.setFolderId(nodeDetail.getNodePK().getId());
                    processImportRecursiveReplicate(
                        reportManager, massiveReport, gedIE, pdcIE, settings);
                  } catch (ImportExportException ex) {
                    massiveReport.setError(UnitReport.ERROR_NOT_EXISTS_OR_INACCESSIBLE_DIRECTORY);
                  }
                  break;
              }
            }
          }
        }
      }
    }
  }