/*
** Luxor - XML User Interface Language (XUL) Toolkit
** Copyright (c) 2001, 2002 by Gerald Bauer
**
** This program is free software.
**
** You may redistribute it and/or modify it under the terms of the GNU
** General Public License as published by the Free Software Foundation.
** Version 2 of the license should be included with this distribution in
** the file LICENSE, as well as License.html. If the license is not
** included with this distribution, you may find a copy at the FSF web
** site at 'www.gnu.org' or 'www.fsf.org', or you may write to the
** Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139 USA.
**
** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
** REDISTRIBUTION OF THIS SOFTWARE.
**
*/

package luxor.util;

import java.net.*;
import java.util.*;
import luxor.status.*;

public class StringUtils
{
   static Logger T = Logger.getLogger( StringUtils.class );

   /*
    *  Perform a series of substitutions. The substitions
    *  are performed by replacing $variable in the target
    *  string with the value of provided by the key "variable"
    *  in the provided hashtable.
    *
    *  @param String target string
    *  @param Hashtable name/value pairs used for substitution
    *  @return String target string with replacements.
    */
   public static String stringSubstitution( String argStr,
         Properties vars )
   {
      StringBuffer argBuf = new StringBuffer();

      for( int pos = 0; pos < argStr.length();  )
      {
         char ch = argStr.charAt( pos );

         switch ( ch )
         {
            case '$':
               StringBuffer nameBuf = new StringBuffer();
               for( ++pos; pos < argStr.length(); ++pos )
               {
                  ch = argStr.charAt( pos );
                  if( ch == '_'
                         || ch == '.'
                         || ch == '-'
                         || Character.isLetterOrDigit( ch ) )
                  {
                     nameBuf.append( ch );
                  }
                  else
                     break;
               }

               if( nameBuf.length() > 0 )
               {
                  String value =
                        ( String ) vars.getProperty( nameBuf.toString() );

                  T.debug( nameBuf.toString() + "=" + value );

                  if( value != null )
                     argBuf.append( value );
               }
               break;
            default:
               argBuf.append( ch );
               ++pos;
               break;
         }
      }
      return argBuf.toString();
   }

}