/*
 * Copyright (c) 2009 JSCAPE
 * 1147 S. 53rd Pl., Mesa, Arizona, 85206, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * JSCAPE. ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with
 * the terms of the license agreement you entered into with JSCAPE.
 *
 */

package com.jscape.util.functor;

import com.jscape.util.Assert;

import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author Alex Usun
 */
public class RegexValueReplacer
        extends UnaryFunction<String, String> {

    private String regex;
    private String replacement;

    /**
     * @param values values
     *
     * @return UnaryFunction instance
     */
    public static UnaryFunction<String, String> make(Map<String, String> values) {
        UnaryFunction<String, String> ret = Identity.instance();

        for (Map.Entry<String, String> entry : values.entrySet()) {
            ret = ret.then(new RegexValueReplacer(entry.getKey(), entry.getValue()));
        }

        return ret;
    }

    /**
     * @param regex       regex
     * @param replacement replacement
     */
    public RegexValueReplacer(String regex, String replacement) {
        Assert.isValidString(regex);
        assertRegexValid(regex);
        this.regex = regex;

        Assert.notNull(replacement);
        this.replacement = replacement;
    }

    /**
     * @param value value
     *
     * @return String instance
     */
    public String evaluate(String value) {
        return value.replaceAll(this.regex, this.replacement);
    }

    /**
     * @param regex regex
     */
    private void assertRegexValid(String regex) {
        Pattern.compile(regex);
    }
}
