001/*
002 *  Copyright 2019 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.odf.ose.export.utils;
017
018import java.util.Collection;
019import java.util.Collections;
020import java.util.List;
021import java.util.Objects;
022import java.util.Optional;
023import java.util.Set;
024import java.util.stream.Collectors;
025
026import org.apache.avalon.framework.service.ServiceException;
027import org.apache.avalon.framework.service.ServiceManager;
028import org.apache.commons.lang3.StringUtils;
029
030import org.ametys.cms.data.ContentValue;
031import org.ametys.cms.repository.Content;
032import org.ametys.core.cache.Cache;
033import org.ametys.odf.ProgramItem;
034import org.ametys.odf.course.Course;
035import org.ametys.odf.enumeration.OdfReferenceTableEntry;
036import org.ametys.odf.enumeration.OdfReferenceTableHelper;
037import org.ametys.odf.orgunit.OrgUnit;
038import org.ametys.odf.ose.export.OSEConstants;
039import org.ametys.odf.ose.export.impl.odf.LogUtils;
040import org.ametys.odf.program.AbstractProgram;
041import org.ametys.odf.program.Container;
042import org.ametys.plugins.odfpilotage.helper.PilotageHelper;
043import org.ametys.plugins.repository.AmetysObjectResolver;
044import org.ametys.plugins.repository.AmetysRepositoryException;
045import org.ametys.runtime.i18n.I18nizableText;
046import org.ametys.runtime.model.ModelHelper;
047
048/**
049 * A retriever used like a helper to retrieve some ODF elements from ODF items.
050 */
051public class ElementRetriever extends PilotageHelper
052{
053    /** Avalon Role */
054    public static final String ROLE = ElementRetriever.class.getName();
055    
056    private static final String __STEPS_BY_ITEM_CACHE_ID = ElementRetriever.class.getName() + "$stepsByItem";
057
058    /** The resolver */
059    protected AmetysObjectResolver _resolver;
060
061    @Override
062    public void service(ServiceManager manager) throws ServiceException
063    {
064        super.service(manager);
065        _resolver = (AmetysObjectResolver) manager.lookup(AmetysObjectResolver.ROLE);
066    }
067
068    @Override
069    public void initialize() throws Exception
070    {
071        if (!_cacheManager.hasCache(__STEPS_BY_ITEM_CACHE_ID)) 
072        {
073            _cacheManager.createRequestCache(__STEPS_BY_ITEM_CACHE_ID,
074                new I18nizableText("plugin.odf-ose", "PLUGINS_ODF_OSE_CACHE_STEPS_BY_ITEM_LABEL"),
075                new I18nizableText("plugin.odf-ose", "PLUGINS_ODF_OSE_CACHE_STEPS_BY_ITEM_DESCRIPTION"),
076                false
077            );
078        }
079    }
080    
081    @Override
082    public Set<Container> getSteps(ProgramItem programItem)
083    {
084        // The cache id is different than its superclass
085        return getYearId()
086                .map(yearId -> _getSteps(programItem, yearId, _cacheManager.get(__STEPS_BY_ITEM_CACHE_ID)))
087                .orElseGet(() -> Set.of());
088    }
089    
090    @Override
091    protected Set<Container> _getStepsToCache(ProgramItem programItem, String yearId, Cache<String, Set<Container>> cache)
092    {
093        return _mustNotExport(programItem) ? Collections.EMPTY_SET : super._getStepsToCache(programItem, yearId, cache);
094    }
095    
096    private boolean _mustNotExport(ProgramItem programItem)
097    {
098        if (programItem instanceof Course || programItem instanceof Container)
099        {
100            return ((Content) programItem).getValue(OSEConstants.NO_OSE_EXPORT_ATTRIBUTE_NAME, false, false);
101        }
102        else
103        {
104            return false;
105        }
106    }
107    
108    /**
109     * Retrieve the {@link OrgUnit}s of a given {@link ProgramItem}
110     * @param programItem The program item
111     * @return the {@link OrgUnit}s of the given program item
112     */
113    public Set<OrgUnit> retrieveOrgUnits(ProgramItem programItem)
114    {
115        return _retrieveOrgUnits(programItem);
116    }
117    
118    private Set<OrgUnit> _retrieveOrgUnits(ProgramItem parent)
119    {
120        return Optional.of(parent)
121                .map(this::_getDirectOrgUnit)
122                .map(Collections::singleton)
123                .orElseGet(() -> _retrieveOrgUnitsFromParents(parent));
124    }
125    
126    private Set<OrgUnit> _retrieveOrgUnitsFromParents(ProgramItem programItem)
127    {
128        return _odfHelper.getParentProgramItems(programItem)
129                .stream()
130                .map(this::_retrieveOrgUnits)
131                .flatMap(Set::stream)
132                .collect(Collectors.toSet());
133    }
134    
135    private OrgUnit _getDirectOrgUnit(ProgramItem programItem)
136    {
137        if (programItem instanceof Course course)
138        {
139            List<String> orgUnitIds = course.getOrgUnits();
140            return _resolveAllAndGetFirst(orgUnitIds, course);
141        }
142        else if (programItem instanceof AbstractProgram abstractProgram)
143        {
144            List<String> orgUnitIds = abstractProgram.getOrgUnits();
145            return _resolveAllAndGetFirst(orgUnitIds, abstractProgram);
146        }
147        else if (programItem instanceof Container container)
148        {
149            List<String> orgUnitIds = container.getOrgUnits();
150            return _resolveAllAndGetFirst(orgUnitIds, container);
151        }
152        return null;
153    }
154    
155    private <T extends ProgramItem & Content> OrgUnit _resolveAllAndGetFirst(Collection<String> orgUnitIds, T programElement)
156    {
157        List<OrgUnit> orgUnits = orgUnitIds.stream()
158                .map(this::_resolve)
159                .filter(Objects::nonNull)
160                .collect(Collectors.toList());
161        
162        if (orgUnits.size() > 1)
163        {
164            LogUtils.programElementWarningOrgUnits(getLogger(), programElement, orgUnits);
165        }
166        
167        return orgUnits.isEmpty() ? null : orgUnits.get(0);
168    }
169    
170    private OrgUnit _resolve(String id)
171    {
172        try
173        {
174            return _resolver.resolveById(id);
175        }
176        catch (AmetysRepositoryException e)
177        {
178            // Silently fail
179            return null;
180        }
181    }
182
183    /**
184     * Retrieve the degrees of a given {@link Container}
185     * @param container The container
186     * @return the degrees of the given container
187     */
188    public Set<OdfReferenceTableEntry> retrieveDegree(Container container)
189    {
190        return _odfHelper.getParentPrograms(container)
191                .stream()
192                .map(p -> p.<ContentValue>getValue(AbstractProgram.DEGREE))
193                .filter(Objects::nonNull)
194                .map(ContentValue::getContentIfExists)
195                .filter(Optional::isPresent)
196                .map(Optional::get)
197                .map(OdfReferenceTableEntry::new)
198                .collect(Collectors.toSet());
199    }
200
201    /**
202     * Get the potential steps holder of the program item. A step is a container of year type and it can be set manually on intermediate courses.
203     * @param programItem The {@link ProgramItem} on which we have to retrieve the potential steps holder
204     * @return the potential steps holder of the program item
205     */
206    public Set<Container> retrieveStepsHolder(ProgramItem programItem)
207    {
208        Optional<String> yearId = getYearId();
209        if (yearId.isPresent())
210        {
211            return _getStepsHolder(programItem, yearId.get(), _cacheManager.get(_STEP_HOLDERS_BY_ITEM_CACHE_ID));
212        }
213        
214        return Set.of();
215    }
216    
217    /**
218     * Get the potential period types of the program item. It can be retrieved on courses or containers. The algorithm doesn't search in the parent of semester containers.
219     * @param programItem The {@link ProgramItem} on which we have to retrieve the potential period types
220     * @return the potential period types of the program item
221     */
222    public Set<OdfReferenceTableEntry> retrievePeriodTypes(ProgramItem programItem)
223    {
224        return getSemesterId()
225            .map(id -> _retrievePeriodTypes(programItem, id))
226            .orElse(Collections.EMPTY_SET);
227    }
228
229    private Set<OdfReferenceTableEntry> _retrievePeriodTypes(ProgramItem programItem, String semesterId)
230    {
231        return _getPeriodType(programItem) // Try to get the period type on the current program item
232            .map(Collections::singleton)
233            .orElseGet(() -> _searchPeriodTypesInParents(programItem, semesterId)); // Or search in the parent program items
234    }
235    
236    private Set<OdfReferenceTableEntry> _searchPeriodTypesInParents(ProgramItem programItem, String semesterId)
237    {
238        if (isContainerOfNature(programItem, semesterId))
239        {
240            return Collections.EMPTY_SET;
241        }
242        
243        // Only if programItem not a semester
244        return _odfHelper.getParentProgramItems(programItem) // Get the direct parent program items
245            .stream()
246            .map(parent -> _retrievePeriodTypes(parent, semesterId)) // Retrieve the period types for all parents
247            .flatMap(Set::stream)
248            .collect(Collectors.toSet());
249    }
250    
251    private Optional<OdfReferenceTableEntry> _getPeriodType(ProgramItem programItem)
252    {
253        return Optional.of(programItem)
254            .map(Content.class::cast) // Cast to Content (ProgramItem is always a Content)
255            .filter(c -> ModelHelper.hasModelItem("period", c.getModel())) // Filter if the attribute "period" is not in the model
256            .map(c -> c.<ContentValue>getValue("period")) // Get the period
257            .flatMap(ContentValue::getContentIfExists)
258            .map(c -> c.<ContentValue>getValue("type")) // Get the period type
259            .flatMap(ContentValue::getContentIfExists)
260            .map(OdfReferenceTableEntry::new);
261    }
262
263    
264    /**
265     * Get the semester container nature identifier.
266     * @return an {@link Optional} of the semester identifier
267     */
268    public Optional<String> getSemesterId()
269    {
270        return Optional.of(_refTableHelper)
271                .map(rth -> rth.getItemFromCode(OdfReferenceTableHelper.CONTAINER_NATURE, "semestre"))
272                .map(OdfReferenceTableEntry::getId)
273                .filter(StringUtils::isNotBlank);
274    }
275}