/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.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.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

package com.queplix.core.client.common;

import java.util.Date;

/**
 * Helps to format values to string.
 *
 * @author Sergey Kozmin
 * @since 05.10.2006, 16:54:04
 */
public class StringUtil {
    public static String getFormattedDate(Date selectedDate) {
        return getDobleDig((selectedDate.getMonth() + 1)) + "/" + getDobleDig(
                selectedDate.getDate()) + "/"
                + (selectedDate.getYear() + 1900) + " " + getDobleDig(
                selectedDate.getHours()) + ":" + getDobleDig(
                selectedDate.getMinutes());
    }

    /**
     * Returns value with the zeros on empty positions
     *
     * @param value     value to be formatted
     * @param positions position count in result string
     * @return value with the zeros on empty positions
     */
    public static String getValueAsString(int value, int positions) {
        String ret = String.valueOf(value);
        if(ret.length() < positions) {
            int zerosAdd = (positions - ret.length());
            for(int i = 0; i < zerosAdd; i++) {
                ret = "0" + ret;
            }
        }
        return ret;
    }

    private static String getDobleDig(int value) {
        return getValueAsString(value, 2);
    }

    /**
     * Determine if string is empty.
     *
     * @param text string to check
     * @return true if string is null or string is empty or contains space characters, false otherwise.
     */
    public static boolean isStringEmpty(String text) {
        return text == null || text.trim().equalsIgnoreCase("");
    }

    /**
     * Convert string sizes in form "123px" to int.
     *
     * @param size to convert
     * @return int value if the parameter is valid, otherwise returns -1
     */
    public static int sizeToPixel(String size) {
        if(size.endsWith("px")) {
            return Integer.parseInt(size.substring(0, size.length() - 2));
        }
        return -1; // incorrect size string
    }

    /**
     * Converts from int to string size.
     *
     * @see #sizeToPixel(String)
     */
    public static String pixelToSize(int pixel) {
        return pixel + "px";
    }

    /**
     * Convert string sizes in form "30%" to int.
     *
     * @param size to convert
     * @return int value if the parameter is valid, otherwise returns -1
     */
    public static int sizeToPercent(String size) {
        if(size.endsWith("%")) {
            return Integer.parseInt(size.substring(0, size.length() - 1));
        }
        return -1; // incorrect size string
    }

    /**
     * Get html tag for image
     *
     * @param path to image
     * @return String &lt;img src='path'&gt;
     */
    public static String imgSrc(String path) {
        return "<img src='" + path + "'>";
    }

    /**
     * Covert null to empty string
     *
     * @param text the string
     * @return text as is if it is not null; otherwise returns empty string ("")
     */
    public static String nullToEmpty(String text) {
        return (text != null) ? text:"";
    }

    public static String htmlToText(String html) {
        if(html == null) {
            return "";
        }
        StringBuffer sbResult = new StringBuffer();
        StringBuffer sbTag = new StringBuffer();
        boolean inTag = false;
        for(int i = 0; i < html.length(); i++) {
            char ch = html.charAt(i);
            if(html.startsWith("&nbsp;", i)) {
                sbResult.append(" ");
                i += 5;
                continue;
            } else if(html.startsWith("&amp;", i)) {
                sbResult.append("&");
                i += 4;
                continue;
            } else if(html.startsWith("&gt;", i)) {
                sbResult.append(">");
                i += 3;
                continue;
            } else if(html.startsWith("&lt;", i)) {
                sbResult.append("<");
                i += 3;
                continue;
            } else if(html.startsWith("&#93;", i)) {
                sbResult.append("]");
                i += 4;
                continue;
            } else if(html.startsWith("&#91;")) {
                sbResult.append("[");
                i += 4;
                continue;
            }

            if(inTag) {
                if(ch == '>') {
                    inTag = false;
                    String tag = sbTag.toString().trim().toUpperCase();
                    if(tag.startsWith("BR")) {
                        sbResult.append("\n");
                    }
                } else {
                    sbTag.append(ch);
                }
            } else {
                if(ch == '<') {
                    inTag = true;
                    sbTag = new StringBuffer();
                } else {
                    sbResult.append(ch);
                }
            }
        }
        return sbResult.toString();
    }

    public static String textToHtml(String text) {
        if(text == null) {
            return "";
        }
        StringBuffer sbResult = new StringBuffer();
        for(int i = 0; i < text.length(); i++) {
            char ch = text.charAt(i);
            if(ch == '&') {
                sbResult.append("&amp;");
            } else if(ch == '>') {
                sbResult.append("&gt;");
            } else if(ch == '<') {
                sbResult.append("&lt;");
            } else if(ch == ' ') {
                sbResult.append("&nbsp;");
            } else if(ch == ']') {
                sbResult.append("&#93;");
            } else if(ch == '[') {
                sbResult.append("&#91;");
            } else if(ch == '\n') {
                sbResult.append("<BR>");
            } else {
                sbResult.append(ch);
            }
        }
        return sbResult.toString();
    }

    public static boolean isStringsEquals(String s1, String s2) {
        return s1 == null ? (s1 == s2):s1.equalsIgnoreCase(s2);
    }

    /**
     * Compares two strings. null strings are equivalent to empty string.
     * Empty spaces are removed from the ends by usting String.trim() method.
     *
     * @param s1 first string
     * @param s2 second string
     * @return is two string are equal.
     */
    public static boolean isStringsEqualsIgnoreNulls(String s1, String s2) {
        boolean equals;
        if(isStringEmpty(s1)) {
            equals = isStringEmpty(s2);
        } else {
            equals = s1.trim().equalsIgnoreCase(nullToEmpty(s2).trim());
        }
        return equals;
    }

}
