001/*
002 *  Copyright 2017 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.plugins.odfweb.restrictions.rules;
017
018import java.util.Collection;
019import java.util.Collections;
020import java.util.List;
021import java.util.Objects;
022
023import org.ametys.cms.search.query.OrQuery;
024import org.ametys.cms.search.query.Query;
025import org.ametys.odf.program.Program;
026import org.ametys.plugins.repository.query.expression.Expression;
027import org.ametys.plugins.repository.query.expression.OrExpression;
028
029/**
030 * Or restriction rule
031 */
032public class OdfOrRestrictionRule implements OdfRestrictionRule
033{
034    private final Collection<OdfRestrictionRule> _rules;
035    
036    /**
037     * Or restriction rule constructor
038     * @param rules The list of rules on which a "or" operator must be applied
039     */
040    public OdfOrRestrictionRule(Collection<OdfRestrictionRule> rules)
041    {
042        _rules = rules;
043        _rules.removeAll(Collections.<OdfRestrictionRule>singleton(null));
044    }
045    
046    @Override
047    public boolean contains(Program program)
048    {
049        return _rules.stream().anyMatch(r -> r.contains(program));
050    }
051    
052    @Override
053    public Expression getExpression()
054    {
055        List<Expression> exprs = _rules.stream()
056                .map(OdfRestrictionRule::getExpression)
057                .filter(Objects::nonNull)
058                .toList();
059            
060        if (exprs.isEmpty())
061        {
062            return null;
063        }
064        
065        return new OrExpression(exprs);
066    }
067    
068    public Query getQuery()
069    {
070        List<Query> ruleQueries = _rules.stream()
071            .map(OdfRestrictionRule::getQuery)
072            .filter(Objects::nonNull)
073            .toList();
074        
075        if (ruleQueries.isEmpty())
076        {
077            return null;
078        }
079        
080        return new OrQuery(ruleQueries);
081    }
082    
083    @Override
084    public boolean hasOrgunitRestrictions()
085    {
086        return _rules.stream().anyMatch(OdfRestrictionRule::hasOrgunitRestrictions);
087    }
088}