
package de.ivu.elect.business.exchange.boundary;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

import static java.util.Arrays.asList;
import static org.apache.commons.lang3.StringUtils.defaultString;

// ELECT-6722
public class ExchangeValueDecorators implements Function<String, String> {

    public static final Function<String, String> MESSAGES_DECORATOR_NULL_TO_EMPTY = value -> defaultString(value, "");

    public static final Function<String, String> MESSAGES_DECORATOR_REMOVE_SHY = value -> value.replace("\u00AD", "");

    public static final Function<String, String> MESSAGES_DECORATOR_CSV_INJECTION = value -> {//ELECTVAPP-754
        while (value.startsWith("+") || value.startsWith("-") || value.startsWith("@") || value.startsWith("=")) {
            value = value.replaceAll("^\\+|^\\-|^\\@|^\\=", "");
            // ^\\+| -> ersetze +, wenn es am Anfang(^) steht oder (|)...
        }
        return value;

    };

    private final List<Function<String, String>> decorators;

    public ExchangeValueDecorators() {
        this(asList(//
                MESSAGES_DECORATOR_NULL_TO_EMPTY, //
                MESSAGES_DECORATOR_REMOVE_SHY //
        ));
    }

    public ExchangeValueDecorators(List<Function<String, String>> decorators) {
        super();

        this.decorators = new ArrayList<>(decorators);
    }

    @Override
    public String apply(String message) {
        String result = message;

        for (Function<String, String> decorator : decorators) {
            result = decorator.apply(result);
        }

        return result;
    }
}
