001/*
002 *  Copyright 2020 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;
017
018import java.util.ArrayList;
019import java.util.List;
020import java.util.Map;
021import java.util.Optional;
022
023import org.apache.commons.lang.StringUtils;
024
025import org.ametys.cms.contenttype.MetadataType;
026import org.ametys.cms.search.query.AndQuery;
027import org.ametys.cms.search.query.ContentLanguageQuery;
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.cms.search.ui.model.impl.AbstractCustomSearchUICriterion;
032
033/**
034 * UI criteria for program item context
035 */
036public class ProgramItemContextSearchUICriteria extends AbstractCustomSearchUICriterion
037{
038    public String getFieldId()
039    {
040        return "program.item.context.field";
041    }
042
043    public Operator getOperator()
044    {
045        // Not suppose to be used
046        return Operator.EQ;
047    }
048    
049    @Override
050    public MetadataType getType()
051    {
052        // Not suppose to be used
053        return MetadataType.STRING;
054    }
055
056    public Query getQuery(Object value, Operator customOperator, Map<String, Object> allValues, String language, Map<String, Object> contextualParameters)
057    {
058        List<Query> queries = new ArrayList<>();
059        
060        Optional<ProgramItem> program = Optional.ofNullable(contextualParameters.get("contentId"))
061            .filter(String.class::isInstance)
062            .map(String.class::cast)
063            .map(id -> _resolver.resolveById(id));
064        
065        if (program.isPresent())
066        {
067            ProgramItem programItem = program.get();
068            queries.add(new StringQuery(ProgramItem.CATALOG, programItem.getCatalog()));
069            
070            String lang = programItem.getLanguage();
071            if (StringUtils.isNotBlank(lang))
072            {
073                queries.add(new ContentLanguageQuery(lang));
074            }
075        }
076        
077        return new AndQuery(queries);
078    }
079}