//   Copyright 2012 Georg-August-Universität Göttingen, Germany
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package de.ugoe.cs.util;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * Helper class that provides methods to simplify working with {@link String}s.
 * </p>
 * 
 * @author Steffen Herbold
 * @version 1.0
 */
final public class StringTools {

    /**
     * <p>
     * Private constructor to prevent initializing of the class.
     * </p>
     */
    private StringTools() {

    }

    /**
     * <p>
     * Simplifies use of operation system specific line separators.
     * </p>
     */
    public final static String ENDLINE = System.getProperty("line.separator");

    /**
     * <p>
     * Replaces all occurrences of {@literal &, <, >, ', and "} with their respective XML entities
     * {@literal &amp;, &lt;, &gt;, &apos;, and &quot;} without destroying already existing
     * entities.
     * </p>
     * 
     * @param str
     *            String where the XML entities are to be replaced
     * @return new String, where the XML entities are used instead of the literals
     */
    public static String xmlEntityReplacement(String str) {
        String result = str;
        if (result != null && !"".equals(result)) {
            result = result.replaceAll("&(?!(?:lt|gt|apos|quot|amp);)", "&amp;");
            result = result.replaceAll("<", "&lt;");
            result = result.replaceAll(">", "&gt;");
            result = result.replaceAll("'", "&apos;");
            result = result.replaceAll("\"", "&quot;");
        }
        return result;
    }
    
    /**
     * <p>
     * Performs an auto completion of the provided prefix using the given potential completions.
     * The method searches for all completions that start with the given prefix and stores them in
     * a subset. It then extends the prefix with characters of the subset of completions as long as
     * the prefix still prefixes all completions in the subset. The result is then returned. If
     * there is no matching completion or if there are several matching completions differing
     * in the succeeding letter, the prefix is returned as is. If there is only one matching
     * completion this completion is returned.
     * </p>
     * 
     * @param prefix      the prefix to be further completed
     * @param completions the potential completions of the prefix
     * 
     * @return as described
     */
    public static String autocomplete(String prefix, String[] completions) {
        List<String> matchingCompletions = new ArrayList<String>();
        for (String completion : completions) {
            if (completion.startsWith(prefix)) {
                matchingCompletions.add(completion);
            }
        }
        
        StringBuffer completedPrefix = new StringBuffer(prefix);
        
        boolean foundCompletion = false;
        
        while (!foundCompletion) {
            char nextCompletionChar = 0;
            for (String completion : matchingCompletions) {
                if (completion.length() > completedPrefix.length()) {
                    if (nextCompletionChar == 0) {
                        nextCompletionChar = completion.charAt(completedPrefix.length());
                    }
                    else if (nextCompletionChar != completion.charAt(completedPrefix.length())) {
                        foundCompletion = true;
                    }
                }
                else {
                    foundCompletion = true;
                }
            }
            
            if (!foundCompletion && (nextCompletionChar != 0)) {
                completedPrefix.append(nextCompletionChar);
            }
            else {
                foundCompletion = true;
            }
        }
        
        return completedPrefix.toString();
    }
}
