001/*
002 *  Copyright 2016 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.cms.search.solr.field;
017
018import java.util.List;
019import java.util.Locale;
020import java.util.Optional;
021
022import org.apache.avalon.framework.context.Context;
023import org.apache.cocoon.components.ContextHelper;
024import org.apache.commons.lang3.StringUtils;
025
026import org.ametys.cms.search.cocoon.SearchAction;
027
028/**
029 * String generic search field.
030 */
031public class MultilingualStringSearchField extends AbstractMetadataSearchField
032{
033    private Optional<Context> _context;
034
035    /**
036     * Build a multilingual string search field.
037     * @param path The field path.
038     * @param context The context
039     */
040    public MultilingualStringSearchField(String path, Optional<Context> context)
041    {
042        super(path);
043        _context = context;
044    }
045    
046    /**
047     * Build a multilingual string search field.
048     * @param joinPaths The join field paths
049     * @param finalPath The final field path.
050     * @param context The context
051     */
052    public MultilingualStringSearchField(List<String> joinPaths, String finalPath, Optional<Context> context)
053    {
054        super(joinPaths, finalPath);
055        _context = context;
056    }
057
058    @Override
059    protected String _getSortFieldSuffix()
060    {
061        return getCurrentLanguage(_context)
062                .map("_"::concat)
063                .orElse(StringUtils.EMPTY)
064                + "_s_sort";
065    }
066    
067    /**
068     * Gets the current language
069     * @param context The context
070     * @return the current language
071     */
072    protected static Optional<String> getCurrentLanguage(Optional<Context> context)
073    {
074        return context
075                .map(ContextHelper::getRequest)
076                .map(r -> r.getAttribute(SearchAction.SEARCH_LOCALE))
077                .filter(Locale.class::isInstance)
078                .map(Locale.class::cast)
079                .map(Locale::getLanguage);
080    }
081    
082    @Override
083    protected String _getFacetFieldSuffix()
084    {
085        return "_s_dv";
086    }
087
088}