/*
 * ICESOFT COMMERCIAL SOURCE CODE LICENSE V 1.1
 *
 * The contents of this file are subject to the ICEsoft Commercial Source
 * Code License Agreement V1.1 (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.icesoft.com/license/commercial-source-v1.1.html
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations under
 * the License.
 *
 * Copyright 2009-2015 ICEsoft Technologies Canada, Corp. All Rights Reserved.
 */
package com.icesoft.faces.facelets.component.util;

/**
 * Convenience class used to provide various common manipulation methods and functionality
 */
public class StringUtil {

    /**
     * Method to fix the case of the passed string
     * This will basically ensure only the first letter of each word is capitalized
     *
     * @param inString the string to capitalize
     * @return capitalized result
     */
    public static String fixCapitalization(String inString) {
        StringBuffer str = new StringBuffer(inString.trim().toLowerCase());

        if (str.length() == 0) {
            return str.toString();
        }

        Character nextChar;
        int i = 0;
        nextChar = str.charAt(i);
        while (i < str.length()) {
            str.setCharAt(i++, Character.toUpperCase(nextChar.charValue()));

            if (i == str.length()) {
                return str.toString();
            }

            // Look for whitespace
            nextChar = str.charAt(i);
            while (i < str.length() - 2 && !Character.isWhitespace(nextChar.charValue())) {
                nextChar = str.charAt(++i);
            }

            if (!Character.isWhitespace(nextChar.charValue())) {
                // If not whitespace, we must be at end of string
                return str.toString();
            }

            // Remove all but first whitespace
            nextChar = str.charAt(++i);
            while (i < str.length() && Character.isWhitespace(nextChar.charValue())) {
                str.deleteCharAt(i);
                nextChar = str.charAt(i);
            }
        }

        return str.toString();
    }

}
