/*
** Caramel - Core Java Toolbox
** Copyright (c) 2001, 2002, 2003 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 caramel.util;

import java.net.*;
import java.text.*;
import java.util.*;
import houston.*;

public class StringUtils
{
   static Logger T = Logger.getLogger( StringUtils.class );
   private static SimpleDateFormat _dateTimeFormatter = new SimpleDateFormat( "dd.MM.yyyy HH:mm" );

   private static SimpleDateFormat _timeFormatter = new SimpleDateFormat( "HH:mm" );

   public static String getPrettyPrintedDate( Date date )
   {
      Date now = new Date();

      // is it today?
      if( date.getDate() == now.getDate()
             && date.getMonth() == now.getMonth()
             && date.getYear() == now.getYear() )
      {
         return "Today " + _timeFormatter.format( date );
      }
      else
      {
         // it's not today, calculate difference in days

         return _dateTimeFormatter.format( date );
      }
   }

   public static String getPrettyPrintedDateDifference( Date date, boolean useDays )
   {
      Date now = new Date();

      // is it today?
      if( date.getDate() == now.getDate()
             && date.getMonth() == now.getMonth()
             && date.getYear() == now.getYear() )
      {
         /*
          *  return empty string
          */
         return "";
      }
      else
      {
         StringBuffer buf = new StringBuffer();

         long diff = now.getTime() - date.getTime();

         // make sure diffInDays rounds up/down to the next integer (e.g. 0.45 -> 1)
         if( diff > 0 )
            diff += ( 1000 * 60 * 60 * 24 ) - 1;
         // milli*seconds*minutes*hours = 1 day
         else
            diff -= ( 1000 * 60 * 60 * 24 ) - 1;

         long diffInDays = diff / ( 1000 * 60 * 60 * 24 );

         if( diffInDays > 0 )
         {
            buf.append( "" + diffInDays );

            if( useDays )
            {
               if( diffInDays == 1 )
                  buf.append( " day ago" );
               else
                  buf.append( " days ago" );
            }
         }
         else
         {
            buf.append( "" + ( -diffInDays ) );

            if( useDays )
            {
               if( diffInDays == -1 )
                  buf.append( " day" );
               else
                  buf.append( " days" );
            }
         }

         return buf.toString();
      }
   }

   public static String fillTemplate(
         Properties vars, String argStr )
   {
      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 =
                        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();
   }

   public static String prettyPrintDouble( double value, int digits )
   {
      NumberFormat form = NumberFormat.getNumberInstance( Locale.US );

      form.setMinimumFractionDigits( digits );
      form.setMaximumFractionDigits( digits );

      return form.format( value );
   }

   public static String prettyPrintDuration( long duration_in_secs )
   {
      long secs = duration_in_secs % 60;
      long minutes = duration_in_secs / 60;

      StringBuffer buf = new StringBuffer();

      if( minutes < 10 )
         buf.append( "0" + minutes + ":" );
      else
         buf.append( "" + minutes + ":" );

      if( secs < 10 )
         buf.append( "0" + secs );
      else
         buf.append( "" + secs );

      return buf.toString();
   }

   public static String prettyPrintFileSize( long size )
   {
      if( size == -1 )
         return "n/a";

      if( size == 0 )
         return "0 k";

      // use kilobytes only (1028 bytes) for now
      if( size < 1028 )
      {
         return "1 k";
         // return form.format( size ) + " bytes";
      }

      NumberFormat form = NumberFormat.getNumberInstance( Locale.US );

      size = size / 1028;

      return form.format( size ) + " k";
   }

   public static String removeTrailingNewlines( String line )
   {
      // remove trailing newlines
      int cutoffPoint = line.length();
      while( cutoffPoint > 0
             && ( line.charAt( cutoffPoint - 1 ) == 10
             || line.charAt( cutoffPoint - 1 ) == 13 ) )
      {
         cutoffPoint--;
      }

      return line.substring( 0, cutoffPoint );
   }

   // convienience method
   public static String[] split( String line )
   {
      return split( line, ",;:|" );
   }

   public static String[] split( String line, String delim )
   {
      ArrayList l = new ArrayList();
      StringTokenizer t = new StringTokenizer( line, delim );
      while( t.hasMoreTokens() )
         l.add( t.nextToken() );

      return ( String[] ) l.toArray( new String[0] );
   }

   /*
    *  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(
         Properties vars, String argStr )
   {
      return fillTemplate( vars, argStr );
   }

}