/**
 * @(#)file    StringUtil2.java
 * @(#)author  OK
 * @(#)version 1.0
 * @(#)date    2014. 07. 15
 * @(#)since   JDK 1.4.2
 *
 * Copyright (c) www.udapsoft.co.kr, Inc.
 * All rights reserved.
 * This software is the proprietary information of udapsoft, Inc.
 * 
 */
package com.udapsoft.waf.common.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.StringTokenizer;

public class StringUtil2
{

    protected StringUtil2()
    {
    }

    public static String getPrintStackTrace(Throwable e)
    {
        return getPrintStackTrace(e, false);
    }

    public static String getPrintStackTrace(Throwable e, boolean isHTML)
    {
        if(e == null)
            return "";
        String message = null;
        StringWriter writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        message = writer.toString();
        if(isHTML)
            message = convertWebText(message);
        return message;
    }

    public static String convertWebText(String str)
    {
        str = replace(str, "\r", "\\r");
        str = replace(str, "\n", "\\n");
        return str;
    }

    public static String filter(String message)
    {
        if(message == null)
            return null;
        char content[] = new char[message.length()];
        message.getChars(0, message.length(), content, 0);
        StringBuffer result = new StringBuffer(content.length + 50);
        for(int i = 0; i < content.length; i++)
            switch(content[i])
            {
            case 60: // '<'
                result.append("&lt;");
                break;

            case 62: // '>'
                result.append("&gt;");
                break;

            case 38: // '&'
                result.append("&amp;");
                break;

            case 34: // '"'
                result.append("&quot;");
                break;

            default:
                result.append(content[i]);
                break;
            }

        return result.toString();
    }

    public static String removeChar(String str, char c)
    {
        if(str == null)
            return null;
        if(str.indexOf(c) == -1)
            return str;
        StringBuffer sb = new StringBuffer();
        char chars[] = str.toCharArray();
        for(int i = 0; i < chars.length; i++)
            if(c != chars[i])
                sb.append(chars[i]);

        return sb.toString();
    }

    public static String replace(String line, String oldStr, String newStr)
    {
        if(line == null || line.length() == 0)
            return "";
        for(int index = 0; (index = line.indexOf(oldStr, index)) >= 0; index += newStr.length())
            line = line.substring(0, index) + newStr + line.substring(index + oldStr.length());

        return line;
    }

    public static String formatZipcode(String code)
    {
        if(code == null)
        {
            return "";
        } else
        {
            StringBuffer sb = new StringBuffer(code);
            sb.insert(3, "-");
            return sb.toString();
        }
    }

    public static String formatRegNumber(String number)
    {
        if(number == null || number.length() < 7)
        {
            return "";
        } else
        {
            StringBuffer sb = new StringBuffer(number);
            sb.insert(3, "-").insert(6, "-");
            return sb.toString();
        }
    }

    public static String getString(String str)
    {
        return getString(str, "");
    }

    public static String getString(String str, String defaultv)
    {
        return str != null ? str : defaultv;
    }

    public static String getHtmlString(String str)
    {
        if(str == null || str.equals(""))
            str = "&nbsp;";
        return str;
    }

    public static int getInt(String str)
    {
        return getInt(str, 0);
    }

    public static int getInt(String str, int defaultv)
    {
        int i = 0;
        try
        {
            i = Integer.parseInt(str);
        }
        catch(NumberFormatException nfe)
        {
            i = defaultv;
        }
        return i;
    }

    public static String lpad(String str, int len)
    {
        return lpad(str, len, '0');
    }

    public static String lpad(String str, int len, char pad)
    {
        int count = 0;
        if(str != null)
        {
            count = len - str.length();
        } else
        {
            str = "";
            count = len;
        }
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < count; i++)
            sb.append(pad);

        return sb.append(str).toString();
    }

    public static String rpad(String str, int len)
    {
        return rpad(str, len, '0');
    }

    public static String rpad(String str, int len, char pad)
    {
        int count = 0;
        if(str != null)
        {
            count = len - str.length();
        } else
        {
            str = "";
            count = len;
        }
        StringBuffer sb = new StringBuffer(str);
        for(int i = 0; i < count; i++)
            sb.append(pad);

        return sb.toString();
    }

    public static String[] split(String data, int rule[])
    {
        String parsed[] = new String[rule.length];
        byte bytes[] = data.getBytes();
        int byteslen = Array.getLength(bytes);
        int pointer = 0;
        for(int i = 0; i < rule.length; i++)
        {
            if(byteslen < pointer)
                parsed[i] = new String("");
            else
                parsed[i] = new String(bytes, pointer, rule[i]);
            pointer += rule[i];
        }

        return parsed;
    }

    public static String[] split(String str, String delim)
    {
        StringTokenizer st = new StringTokenizer(str, delim);
        int size = st.countTokens();
        String tokens[] = new String[size];
        for(int i = 0; st.hasMoreTokens(); i++)
            tokens[i] = st.nextToken();

        return tokens;
    }

    public static String formatJumin(String juminString)
    {
        if(juminString == null)
            return "";
        if(juminString.length() != 13)
            return juminString;
        else
            return juminString.substring(0, 6) + "-" + juminString.substring(6);
    }

    public static String formatCurrency(String amountString)
    {
        try
        {
            double amount = Double.parseDouble(amountString);
            return formatCurrency(amount);
        }
        catch(NumberFormatException ex)
        {
            return amountString;
        }
    }

    public static String formatCurrency(int amountInt)
    {
        double amount = (new Integer(amountInt)).doubleValue();
        return formatCurrency(amount);
    }

    public static String formatCurrency(double amount)
    {
        DecimalFormat df = (DecimalFormat)NumberFormat.getCurrencyInstance();
        String pattern = "###,###,###,###,###,##0.00";
        df.applyPattern(pattern);
        return df.format(amount);
    }
    
    /////////////// 기존 메소드에 추가. 2007.08.27
    public static String formatCurrency(String amountString, int nPointPosCnt)
    {
        try
        {
            double amount = Double.parseDouble(amountString);
            return formatCurrency(amount, nPointPosCnt);
        }
        catch(NumberFormatException ex)
        {
            return amountString;
        }
    }

    public static String formatCurrency(int amountInt, int nPointPosCnt)
    {
        double amount = (new Integer(amountInt)).doubleValue();
        return formatCurrency(amount, nPointPosCnt);
    }

    public static String formatCurrency(double amount, int nPointPosCnt)
    {
        DecimalFormat df = (DecimalFormat)NumberFormat.getCurrencyInstance();
        //String pattern = "###,###,###,###,###,##0.00";
        String pattern = "###,###,###,###,###,##0";
        
        // 소숫점 위치가 2보다 큰 경우만 처리한다.
        if(nPointPosCnt > Formatter2.DEF_CURRENCY_POINT_POS)
        {
        	for(int ii=0;ii<(nPointPosCnt-Formatter2.DEF_CURRENCY_POINT_POS);ii++)
        	{
        		if(ii == 0)
        		{
        			pattern += ".";
        		}
        		pattern += "0";
        	}
        }
        
        df.applyPattern(pattern);
        return df.format(amount);
    }
    

    public static String getToken(int index, String str, String token)
    {
        StringTokenizer st = new StringTokenizer(str, token);
        String value = "";
        for(int i = 0; st.hasMoreTokens(); i++)
        {
            if(index == i)
            {
                value = st.nextToken();
                break;
            }
            st.nextToken();
        }

        return value;
    }

    public static String[] toArray(String str, String delim)
    {
        if(str == null)
            return new String[0];
        StringTokenizer st = new StringTokenizer(str, delim);
        String tokens[] = new String[st.countTokens()];
        for(int i = 0; st.hasMoreTokens(); i++)
            tokens[i] = st.nextToken();

        return tokens;
    }

    public static String dateToDtDate(String str)
    {
        if(str.length() == 8)
            str = str.substring(4, 6) + "." + str.substring(6, 8);
        return str;
    }

    public static String formatRate(String pRate)
    {
        return formatRate(pRate, 2);
    }

    public static String formatRate(String pRate, int pPost)
    {
        String vReturn = null;
        if(pRate == null)
            return "";
        if(pPost <= 0)
            return pRate;
        if(pRate.length() <= pPost)
        {
            return pRate;
        } else
        {
            int vIndex = pRate.length() - pPost;
            vReturn = formatCurrency(pRate.substring(0, vIndex));
            vReturn = vReturn + "." + pRate.substring(vIndex);
            return vReturn;
        }
    }

    public static String hide(String exposed, int beginIndex, int endIndex)
    {
        if(exposed == null)
            return "";
        if(exposed.length() < beginIndex)
            beginIndex = exposed.length();
        if(exposed.length() < endIndex)
            endIndex = exposed.length();
        StringBuffer buffer = new StringBuffer();
        for(int i = 0; i < exposed.length(); i++)
            if(i >= beginIndex && i < endIndex)
                buffer.append("*");
            else
                buffer.append(exposed.charAt(i));

        return buffer.toString();
    }

    public static String hide(String exposed, int beginIndex)
    {
        if(exposed == null)
            return "";
        else
            return hide(exposed, beginIndex, exposed.length());
    }

    public static String hideRear(String exposed, int rearIndex)
    {
        if(exposed == null)
            exposed = "";
        exposed.trim();
        if(exposed.length() < rearIndex)
            rearIndex = exposed.length();
        return hide(exposed, exposed.length() - rearIndex, exposed.length());
    }

    public static String hideAccount(String account)
    {
        return hideRear(account, 4);
    }

    public static String hideAccount(String account, int cnt)
    {
        return hideRear(account, cnt);
    }

    public static String hideSSN(String ssn)
    {
        return hideRear(ssn, 7);
    }

    public static String hideCardNo(String card)
    {
        if(card == null)
            return "";
        else
            return hide(card.trim(), 4, 12);
    }

    public static String space(int len)
    {
        StringBuffer buffer = new StringBuffer();
        for(int i = 0; i < len; i++)
            buffer.append(" ");

        return buffer.toString();
    }

    public static void writeSpace(StringBuffer buffer, int len)
    {
        for(int i = 0; i < len; i++)
            buffer.append(" ");

    }

    public static void writeZero(StringBuffer buffer, int len)
    {
        for(int i = 0; i < len; i++)
            buffer.append("0");

    }

    public static void writeLeadingZero(StringBuffer buffer, String subject, int len)
    {
        writeZero(buffer, len - subject.length());
        buffer.append(subject);
    }

    public static void writeTailedSpace(StringBuffer buffer, String subject, int len)
    {
        buffer.append(subject);
        writeSpace(buffer, len - subject.length());
    }
}