001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools.template_engine;
003
004import org.openstreetmap.josm.data.osm.search.SearchCompiler.Match;
005
006import java.util.Objects;
007
008/**
009 * Conditional {@link TemplateEntry} that executes another template in case a search expression applies
010 * to the given data provider.
011 */
012public class SearchExpressionCondition implements TemplateEntry {
013
014    private final Match condition;
015    private final TemplateEntry text;
016
017    /**
018     * Creates a new {@link SearchExpressionCondition}.
019     * @param condition the match condition that is checked before applying the child template
020     * @param text the child template to execute in case the condition is fulfilled
021     */
022    public SearchExpressionCondition(Match condition, TemplateEntry text) {
023        this.condition = condition;
024        this.text = text;
025    }
026
027    @Override
028    public void appendText(StringBuilder result, TemplateEngineDataProvider dataProvider) {
029        text.appendText(result, dataProvider);
030    }
031
032    @Override
033    public boolean isValid(TemplateEngineDataProvider dataProvider) {
034        return dataProvider.evaluateCondition(condition);
035    }
036
037    @Override
038    public String toString() {
039        return condition + " '" + text + '\'';
040    }
041
042    @Override
043    public int hashCode() {
044        return Objects.hash(condition, text);
045    }
046
047    @Override
048    public boolean equals(Object obj) {
049        if (this == obj)
050            return true;
051        if (obj == null || getClass() != obj.getClass())
052            return false;
053        SearchExpressionCondition other = (SearchExpressionCondition) obj;
054        if (condition == null) {
055            if (other.condition != null)
056                return false;
057        } else if (!condition.equals(other.condition))
058            return false;
059        if (text == null) {
060            if (other.text != null)
061                return false;
062        } else if (!text.equals(other.text))
063            return false;
064        return true;
065    }
066}