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.plugins.forms.question.autofill;
017
018import java.util.ArrayList;
019import java.util.HashMap;
020import java.util.List;
021import java.util.Map;
022
023import org.ametys.plugins.forms.repository.FormQuestion;
024import org.ametys.runtime.model.ElementDefinition;
025import org.ametys.runtime.model.ModelItem;
026import org.ametys.runtime.model.ViewElement;
027import org.ametys.runtime.model.ViewItem;
028import org.ametys.runtime.model.type.ModelItemTypeConstants;
029import org.ametys.runtime.parameter.DefaultValidator;
030
031/**
032 * Class for adding custom value as default value in text  fields
033 */
034public class CustomValueAutoFillSource extends AbstractStaticAutoFillSource
035{
036    /** Constant for default value attribute. */
037    public static final String ATTRIBUTE_DEFAULT_VALUE = "default-value";
038    
039
040    /** Map of ModelItems specific to CustomValueAutoFillSource */
041    protected Map<String, ModelItem> _autoFillItems;
042    
043    public String getAutofillValue(FormQuestion question)
044    {
045        return question.getValue(ATTRIBUTE_DEFAULT_VALUE);
046    }
047
048    public Map<String, ModelItem> getModelItems()
049    {
050        _autoFillItems = new HashMap<>();
051
052        //DEFAULT VALUE
053        ElementDefinition defaultValue = _formElementDefinitionHelper.getElementDefinition(ATTRIBUTE_DEFAULT_VALUE, ModelItemTypeConstants.STRING_TYPE_ID, "PLUGINS_FORMS_QUESTIONS_DIALOG_SIMPLE_TEXT_DEFAULT_VALUE", "PLUGINS_FORMS_QUESTIONS_DIALOG_SIMPLE_TEXT_DEFAULT_VALUE_DESC", new DefaultValidator(null, true));
054        _autoFillItems.put(ATTRIBUTE_DEFAULT_VALUE, defaultValue);
055        
056        return _autoFillItems;
057    }
058
059    public List<ViewItem> getViewElements()
060    {
061        List<ViewItem> viewElements = new ArrayList<>();
062        
063        ViewElement defaultValue = new ViewElement();
064        defaultValue.setDefinition((ElementDefinition< ? >) _autoFillItems.get(ATTRIBUTE_DEFAULT_VALUE));
065        viewElements.add(defaultValue);
066        
067        return viewElements;
068    }
069
070    public boolean isCacheable(FormQuestion question)
071    {
072        return true;
073    }
074
075}