import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.swing.*;

/**
 * User: armond
 */
public final class GeneralUtils
{
	private static File skinDirectory;

	public static void setSkinDirectory( File skinDirectory )
	{
		GeneralUtils.skinDirectory = skinDirectory;
	}

	public static void log(String str, Throwable e)
	{
		if( str!=null )
			System.out.println(str);

		if( e!=null )
			e.printStackTrace(System.out);
	}

	public static String readTextFile(File file)
	{
		if( file!=null && file.exists() && file.length()>0 )
		{
			try
			{
				return se.datadosen.util.IO.readTextFile(file);
			}
			catch( IOException e )
			{
				log("Error reading text file!", e);
				return "";
			}
		}
		else
			return "";
	}

	public static void copyFile(File src, File dest)
	{
		try
		{
			se.datadosen.util.IO.copyFile(src, dest, true);
		}
		catch( IOException e )
		{
			log("Error copying file!", e);
		}
	}

	public static String formatBigTemplate(String template, Object[] args)
	{
		StringBuffer result = new StringBuffer();

		for( int i=0; i<template.length(); i++ )
		{
			char ch = template.charAt(i);

			if( ch=='{' )
			{
				int index = template.indexOf("}", i);

				 if( index>i+1 )
				 {
					try
					{
						int arg_no = Integer.parseInt( template.substring(i+1, index) );
						Object arg = args[arg_no];

						result.append( (arg==null) ? arg : arg.toString() );
						i = index;
						continue;
					}
					catch( Exception e )
					{
					}
				 }
			}

			result.append(ch);
		}
		return result.toString();
	}

	public static String replaceAll(String str, String old, String replacement)
	{
		if( isEmptyString(str) )
			return str;

		StringBuffer result = new StringBuffer(str);
		int index = -1;

		while( (index = result.toString().indexOf(old, (index==-1) ? 0 : index+replacement.length()))!=-1 )
			result.replace(index, index+old.length(), replacement);
		return result.toString();

		//return str.replaceAll(old, replacement);
	}

	public static boolean isEmptyString(Object obj)
	{
		return( obj==null || obj.toString().trim().equals("") );
	}

	public static String clearHtmlCode(String str)
	{
		if( isEmptyString(str) || (str.indexOf("<")==-1 && str.indexOf("\"")==-1) )
			return str;

		StringBuffer buf = new StringBuffer();

		for( int i=0; i<str.length(); i++ )
		{
			char ch = str.charAt(i);

			if( ch=='<' )
			{
				i = str.indexOf(">", i);
				if( i==-1 )
					break;
			}
			else if( ch!='\"' )
				buf.append(ch);
		}

		return buf.toString();
	}

	public static Dimension getImageDimension(File image, int max_width, int max_height)
	{
		if( image==null || !image.exists() )
			return new Dimension(max_width, max_height);

		try
		{
			return getImageDimensionImpl(image, max_width, max_height);
		}
		catch( MalformedURLException e )
		{
			log("Error while calculating the dimension of the image!", e);
			return new Dimension(max_width, max_height);
		}
	}

	private static Dimension getImageDimensionImpl(File image, int max_width, int max_height) throws MalformedURLException
	{
		ImageIcon imageIcon = new ImageIcon(image.toURL());
		Dimension size = new Dimension(imageIcon.getIconWidth(), imageIcon.getIconHeight());

		// By Igor Lubashev: A fix to OUT-OF-MEMORY problem! Seems the JVM does not free the memory used by this object.
		imageIcon.getImage().flush();

		// This shouldn't occur normally!
		if( size.width<=0 || size.height<=0 )
		{
			size.width = max_width;
			size.height = max_height;
		}

		/*if( size.width>max_width )
		{
			size.height = (size.height * max_width) / size.width;
			size.width = max_width;
		}

		if( size.height>max_height )
		{
			size.width = (size.width * max_height) / size.height;
			size.height = max_height;
		}*/

		return size;
	}

	public static String appendString(String main_str, String str_to_append, boolean tooltip)
	{
		String separator = tooltip ? " * " : " <br/>\n";

		return appendString(main_str, str_to_append, separator);
	}

	public static String appendString(String main_str, String str_to_append, String separator)
	{
		if( isEmptyString(str_to_append) )
			return main_str;

		String result = main_str;

		if( result!=null && !result.trim().equals("") )
			result += separator;
		else
			result = "";

		return result + str_to_append;
	}

	public static String convertToString(Object obj)
	{
		if( obj==null )
			return null;
		return obj.toString();
	}

	// Strip non-numeric ending on strings and convert result to integer
	public static int convertToInteger(Object obj)
	{
		if( isEmptyString(obj) )
			return 0;

		String str = obj.toString();
		int i;

		for (i=0; i<str.length(); i++)
		{
			char c = str.charAt(i);
			if (!Character.isDigit(c))
				break;
		}
		if( i>0 )
			return Integer.parseInt(str.substring(0,i));
		else
			return 0;
	}

	// Strip non-numeric ending on strings and convert result to double
	public static double convertToDouble(Object obj)
	{
		if( isEmptyString(obj) )
			return 0;

		String str = obj.toString();
		int i;

		for (i=0; i<str.length(); i++)
		{
			char c = str.charAt(i);
			if (!Character.isDigit(c) && c!='.' && c!='+' && c!='-' )
				break;
		}
		if( i>0 )
			return Double.parseDouble(str.substring(0,i));
		else
			return 0;
	}

	public static File ensureParentFoldersExist( File file )
	{
		file.getParentFile().mkdirs();
		return file;
	}

	public static String replaceFileExtension(String path, String replace)
	{
		int index = path.indexOf( "." );

		if( index>=path.length() - 1 || index<=0 )
			return path + replace;

		return path.substring( 0, index ) + replace;
	}

}
