001/*
002 *  Copyright 2023 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.observation;
017
018import java.util.Map;
019import java.util.Optional;
020
021import org.apache.avalon.framework.service.ServiceException;
022import org.apache.avalon.framework.service.ServiceManager;
023import org.apache.avalon.framework.service.Serviceable;
024
025import org.ametys.cms.ObservationConstants;
026import org.ametys.cms.repository.Content;
027import org.ametys.core.observation.Event;
028import org.ametys.core.observation.Observer;
029import org.ametys.odf.coursepart.CoursePart;
030import org.ametys.odf.enumeration.OdfReferenceTableHelper;
031import org.ametys.runtime.plugin.component.AbstractLogEnabled;
032
033/**
034 * Observer to update course part title on course (only on course parts holded by the course) or course part modification.
035 */
036public class CoursePartTitleObserver extends AbstractLogEnabled implements Observer, Serviceable
037{
038    /** The ODF reference table helper */
039    protected OdfReferenceTableHelper _odfRefTableHelper;
040    
041    public void service(ServiceManager manager) throws ServiceException
042    {
043        _odfRefTableHelper = (OdfReferenceTableHelper) manager.lookup(OdfReferenceTableHelper.ROLE);
044    }
045    
046    @Override
047    public boolean supports(Event event)
048    {
049        if (event.getId().equals(ObservationConstants.EVENT_CONTENT_MODIFIED))
050        {
051            Content content = (Content) event.getArguments().get(ObservationConstants.ARGS_CONTENT);
052            return content instanceof CoursePart;
053        }
054        
055        return false;
056    }
057
058    @Override
059    public int getPriority(Event event)
060    {
061        return 0;
062    }
063
064    @Override
065    public void observe(Event event, Map<String, Object> transientVars) throws Exception
066    {
067        CoursePart coursePart = (CoursePart) event.getArguments().get(ObservationConstants.ARGS_CONTENT);
068        
069        String coursePartTitle =
070            Optional.of(coursePart)
071                .map(CoursePart::getNature)
072                .map(nature -> _odfRefTableHelper.getItemCode(nature))
073                .orElse("N/D");
074        
075        coursePart.setTitle(coursePartTitle);
076        coursePart.saveChanges();
077    }
078}