/*
 * $Id: StringUtils.java,v 1.15 2006/09/29 21:10:10 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: StringUtils.java,v $
 * Revision 1.15  2006/09/29 21:10:10  marbobo
 * + Sucheoptimiert
 *
 * Revision 1.14  2006/03/12 20:44:25  marbobo
 * + replaceSpecialChars() an Unicode angepasst
 *
 * Revision 1.13  2006/02/23 13:03:24  lawern
 * replaceSpecialChars eingefügt
 *
 * Revision 1.12  2005/02/09 10:25:36  lawern
 * Anpassung des WebDavServlet wegen Entity-Kodierung in der DB.
 *
 * Revision 1.11  2004/11/10 15:02:46  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.10  2004/07/20 08:46:28  jonyp
 * added copyright info + cvs log
 *
 *
 */
package vkc.util;

import vkc.misc.VKCLogManager;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;

import java.util.HashMap;
import java.util.Locale;


public class StringUtils {
    /**
     * Method checks whether a email address conforms to the pattern +@+.+
     */
    public final static boolean isEmailValid(String email) {
        email = normalize(email);

        int indexAt = email.indexOf('@');

        if (indexAt <= 0) {
            return false;
        }

        int indexDot = email.indexOf('.', indexAt + 2);

        if (indexDot <= 0) {
            return false;
        }

        if (indexDot == (email.length() - 1)) {
            return false;
        }

        return true;
    }

    /**
     * Method 'normalizes' a string
     * <p>
     * @param s - string that needs to be normalized
     * @return empty string id parameter 's' was null. trimmed instance
     * if s was not null
     */
    public final static String normalize(String s) {
        if (s == null) {
            return "";
        }

        return s.trim();
    }

    /**
     * Method converts a string from Winds-CP-1252 to ISO-8859-15 encoding.
     * <p>
     * @param s - string that needs to be vonverted
     * @return empty string id parameter 's' was null. converted und trimmed instance
     * if s was not null
     */
    public final static String encodingAdaptation(String s) {
        if (s == null) {
            return "";
        }

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            switch ((short) c) {
            case 128: //€
                sb.append((char) 164);

                break;

            case 130: //,
                sb.append(',');

                break;

            case 131: //Integral
                sb.append('f');

                break;

            case 132: //unteres "
            case 147: //" einleitend
            case 148: //" abschließend
                sb.append('"');

                break;

            case 133: //...
                sb.append("...");

                break;

            case 134: //Kruzifix
                sb.append('+');

                break;

            case 135: //Doppelkreuz
                sb.append("++");

                break;

            case 136: //^
                sb.append('^');

                break;

            case 137: //Promille
                sb.append("0/00");

                break;

            case 138: //Š
                sb.append((char) 166);

                break;

            case 139: //<
                sb.append('<');

                break;

            case 140: //OE
                sb.append((char) 188);

                break;

            case 142: //Ž
                sb.append((char) 180);

                break;

            case 145: //' einleitend
            case 146: //' abschließend
                sb.append('\'');

                break;

            case 149: //Punkt
                sb.append('*');

                break;

            case 150: //-
                sb.append('-');

                break;

            case 151: //Gedankenstrich
                sb.append('-');

                break;

            case 152:
                sb.append('~');

                break;

            case 153: //TM
                sb.append("TM");

                break;

            case 154: //š
                sb.append((char) 168);

                break;

            case 155: //>
                sb.append('>');

                break;

            case 156: //oe
                sb.append((char) 189);

                break;

            case 158: //ž
                sb.append((char) 184);

                break;

            case 159: //Ÿ
                sb.append((char) 190);

                break;

            default:
                sb.append(c);
            }
        }

        return sb.toString().trim();
    }

    /**
     * Method converts a string from Windows-CP-1252 to ISO-8859-1 encoding.
     * <p>
     * @param s - string that needs to be vonverted
     * @return empty string id parameter 's' was null. converted und trimmed instance
     * if s was not null
     */
    public final static String cp1252numEntityEnc(String s) {
        if (s == null) {
            return "";
        }

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            short num = (short) c;

            if ((num > 127) && (num < 160)) {
                sb.append("&#" + num + ";");
            } else {
                sb.append(c);
            }
        }

        return sb.toString().trim();
    }

    /**
     * Method fills up a string
     * <p>
     * @param s - string object to modify
     * @param c - fill up character
     * @param len - desired length of strig <code>s</code>
     * @return unmodified string if length of s >= len.
     * empty string if s was null. otherwise a string with
     * added characters at end is returned
     */
    public final static String fillUp(String s, char c, int len) {
        if (s == null) {
            s = "";
        }

        if (s.length() >= len) {
            return s;
        }

        StringBuffer sb = new StringBuffer(s);
        int sbLen = sb.length();

        for (int i = sbLen; i < len; i++) {
            sb.append(c);
        }

        return sb.toString();
    }

    public final static String replaceChar(String s, char c, String newStr) {
        if (s == null) {
            return null;
        }

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == c) {
                sb.append(newStr);
            } else {
                sb.append(s.charAt(i));
            }
        }

        return sb.toString();
    }
    
    /**
     * Entfernt alle Sonderzeichen aus dem String
     */
    public final static String replaceSpecialChars(String s) {
        if (s == null) {
            return null;
        }

        StringBuffer sb = new StringBuffer();
        char c;
        for (int i = 0; i < s.length(); i++) {
            c = s.charAt(i);
            if (!Character.isIdentifierIgnorable(c)) {
                sb.append(c);
            }
        }

        return sb.toString();
    }

    public final static String replaceToken(String str, String token,
        String replacement) {
        if ((str == null) || (token == null) || (token.length() == 0) ||
                (replacement == null)) {
            return str;
        }

        StringBuffer sb = new StringBuffer();
        int tokenLen = token.length();
        int index = 0;

        while (true) {
            index = str.indexOf(token);

            if (index < 0) {
                break;
            }

            sb.append(str.substring(0, index));
            sb.append(replacement);
            str = str.substring(index + tokenLen);
        }

        String s = sb.toString() + str;

        return s;
    }

    public final static double parseDouble(String num, Locale l)
        throws ParseException {
        DecimalFormat f = (DecimalFormat) NumberFormat.getInstance(l);

        return f.parse(num).doubleValue();
    }

    public final static String toDecimalString(String s, Locale l) {
        try {
            DecimalFormat f = (DecimalFormat) NumberFormat.getInstance(l);
            f.setMinimumFractionDigits(2);
            f.setMaximumFractionDigits(2);
            f.setGroupingSize(3);

            return toDecimalString(f.parse(s).doubleValue(), l);
        } catch (Exception ex) {
            VKCLogManager.errorLog(StringUtils.class, "", ex.getMessage(), ex);

            return "";
        }
    }

    public final static String toDecimalString(double d, Locale l) {
        DecimalFormat f = (DecimalFormat) NumberFormat.getInstance(l);
        f.setMinimumFractionDigits(2);
        f.setMaximumFractionDigits(2);
        f.setGroupingSize(3);

        return f.format(d);
    }

    public final static String cut(String s, int len) {
        if (s == null) {
            return null;
        }

        if (s.length() < len) {
            return s;
        }

        return s.substring(0, len) + "...";
    }

    public final static String encodeToLetter(Integer integer) {
        if (integer == null) {
            return "";
        }

        HashMap map = new HashMap();
        map.put("-", "n");
        map.put("0", "a");
        map.put("1", "b");
        map.put("2", "c");
        map.put("3", "d");
        map.put("4", "e");
        map.put("5", "f");
        map.put("6", "g");
        map.put("7", "h");
        map.put("8", "i");
        map.put("9", "j");

        String decodedId = "";
        String id = integer.toString();

        if (integer.intValue() < 0) {
            for (int i = 0; i < id.length(); i++) {
                decodedId += (String) map.get("" + id.charAt(i));
            }
        } else {
            for (int i = 0; i < id.length(); i++) {
                decodedId += (String) map.get("" + id.charAt(i));
            }
        }

        return decodedId;
    }

    public final static Integer decodeToInteger(String string) {
        if (isEmpty(string)) {
            return null;
        }

        HashMap map = new HashMap();
        map.put("n", "-");
        map.put("a", "0");
        map.put("b", "1");
        map.put("c", "2");
        map.put("d", "3");
        map.put("e", "4");
        map.put("f", "5");
        map.put("g", "6");
        map.put("h", "7");
        map.put("i", "8");
        map.put("j", "9");

        String value = "";

        for (int i = 0; i < string.length(); i++) {
            if (!map.containsKey("" + string.charAt(i))) {
                return null;
            }

            value += (String) map.get("" + string.charAt(i));
        }

        try {
            return Integer.valueOf(value);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * Method returns true if the string argument is null or its trimmed
     * <p>
     */
    public static final boolean isEmpty(String s) {
        if (s == null) {
            return true;
        }

        return normalize(s).length() == 0;
    }

    public final static String getHtmlFormatted(String s) {
        if (s == null) {
            return "";
        }

        s = StringUtils.replaceToken(s, "\r\n", "<br>");
        s = StringUtils.replaceChar(s, '\r', "<br>");
        s = StringUtils.replaceChar(s, '\n', "<br>");

        return s;
    }
    
    /**
     * Method returns string represention of this long with leading zeros
     */
    public static final String toString(long l) {
		String zero = "0000000000000000000";

		if (l == 0) {
			return zero;
		}
		
		if (l == Long.MAX_VALUE || l == Long.MIN_VALUE) {
			return Long.toString(l);
		}
		
		if (l < 0) {
			String s = Long.toString(-l);
			int length = zero.length() - s.length();
			
			return "-" + zero.substring(0, length) + s;
		}

		String s = Long.toString(l);
		int length = zero.length() - s.length();
		
		return zero.substring(0, length) + s;
    }
    
    /**
     * Method returns string represention of this Long with leading zeros
     */
    public static final String toString(Long l) {
    	if (l != null) {
    		return toString(l.longValue());
    	}
    	
    	return "";
    }
    
    /**
     * Method returns string represention of this int with leading zeros
     */
    public static final String toString(int i) {
		String zero = "0000000000";

		if (i == 0) {
			return zero;
		}
		
		if (i == Integer.MAX_VALUE || i == Integer.MIN_VALUE) {
			return Integer.toString(i);
		}
		
		if (i < 0) {
			String s = Integer.toString(-i);
			int length = zero.length() - s.length();
			
			return "-" + zero.substring(0, length) + s;
		}

		String s = Integer.toString(i);
		int length = zero.length() - s.length();
		
		return zero.substring(0, length) + s;
    }

    /**
     * Method returns string represention of this Integer with leading zeros
     */
    public static final String toString(Integer i) {
    	if (i != null) {
    		return toString(i.intValue());
    	}
    	
    	return "";
    }
}