001/*
002 *  Copyright 2024 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.coursepart.search;
017
018import java.util.ArrayList;
019import java.util.List;
020import java.util.Map;
021
022import org.apache.commons.lang3.StringUtils;
023
024import org.ametys.cms.search.query.AndQuery;
025import org.ametys.cms.search.query.JoinQuery;
026import org.ametys.cms.search.query.NotQuery;
027import org.ametys.cms.search.query.OrQuery;
028import org.ametys.cms.search.query.Query;
029import org.ametys.cms.search.query.Query.Operator;
030import org.ametys.cms.search.query.StringQuery;
031import org.ametys.odf.ProgramItem;
032import org.ametys.odf.course.search.ShareableCourseSearchUICriteria;
033import org.ametys.odf.coursepart.CoursePart;
034
035/**
036 * UI criteria for shareable course part
037 */
038public class ShareableCoursePartSearchUICriteria extends ShareableCourseSearchUICriteria
039{
040    @Override
041    public String getFieldId()
042    {
043        return "shareable.course.part.field";
044    }
045
046    @Override
047    protected Query _getShareableQuery(Object value, Operator customOperator, Map<String, Object> allValues, String language, Map<String, Object> contextualParameters)
048    {
049        List<Query> queries = new ArrayList<>();
050        
051        // Shareable course must be validated
052        queries.add(_getValidatedShareableCourseQuery());
053        
054        if (contextualParameters.containsKey("courseId"))
055        {
056            String courseId = (String) contextualParameters.get("courseId");
057            if (StringUtils.isNotBlank(courseId))
058            {
059                ProgramItem course = _resolver.resolveById(courseId);
060                queries.addAll(_getShareableFieldQueries(course));
061            }
062        }
063        
064        AndQuery query = queries.stream()
065                .filter(q -> q != null)
066                .collect(AndQuery.collector());
067            
068        return new OrQuery(
069            new JoinQuery(query, CoursePart.COURSE_HOLDER), // returns the course parts whose parent course matches the shareable field values of the current course
070            new NotQuery(new StringQuery(CoursePart.COURSE_HOLDER)) // A course part with no holder is considered as shareable (no shareable fields could matched)
071        );
072    }
073}