/**
 * @(#)file   Formatter2.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.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.Date;
import kr.co.hsnc.common.config.WAFConfig;
import kr.co.hsnc.common.util.Base64;
import kr.co.hsnc.common.util.DateUtil;
import kr.co.hsnc.common.util.NumberFormatter;

public final class Formatter2
{
	public final static int DEF_CURRENCY_POINT_POS = 0;		// DEFAULT 소수점 자리수. => 국내공사 0 이다.

    private Formatter2()
    {
    }

    public static String encode(String str)
    {
        if(str == null)
            return "";
        else
            return Base64.encode(str.getBytes());
    }

    public static String decode(String str)
    {
        if(str == null)
        {
            return "";
        } else
        {
            byte bytes[] = Base64.decode(str);
            return new String(bytes);
        }
    }

    public static String formatMMdd(String date)
    {
        return DateUtil.formatMMdd(date);
    }

    public static String formatDate(Date date)
    {
        return formatDate(date, PATTERN_1);
    }

    public static String formatDate(Date date, String pattern)
    {
        return DateUtil.formatDate(date, pattern);
    }

    public static String formatDate(String day)
    {
        return formatDate(day, PATTERN_0, PATTERN_1);
    }

    public static String formatDate4TS(String day)
    {
        return formatDate(day, PATTERN_3, PATTERN_1);
    }

    public static String formatDate(String date, String delim)
    {
        return DateUtil.formatDate(date, delim);
    }

    public static String formatDate(String day, String pattern1, String pattern2)
    {
        return DateUtil.formatDate(day, pattern1, pattern2);
    }

    public static Date parseDate(String day, String pattern)
        throws Exception
    {
        return DateUtil.parseDate(day, pattern);
    }

    public static String formatZipcode(String code)
    {
        return StringUtil2.formatZipcode(code);
    }

    public static String formatRegNumber(String regno)
    {
        return StringUtil2.formatRegNumber(regno);
    }

    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[] 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 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 currency(String amount, int nPointPosCnt)
    {
    	return StringUtil2.formatCurrency(amount, nPointPosCnt);
    }
    // 수정
    public static String currency(String amount)
    {
    	return Formatter2.currency(amount, Formatter2.DEF_CURRENCY_POINT_POS);
    }
    
    // 추가. 소수점 뒷자리수를 받는 메소드 추가.
    public static String formatCurrency(String amount, int nPointPosCnt)
    {
        return StringUtil2.formatCurrency(amount, nPointPosCnt);
    }
    
    // 추가. 금액과 통화구분을 받아 금액과 소수점 넘기기 추가 2010.09.17 박준현
    public static String formatCurrency(String amount, String currency)
    {
    	int nPointPosCnt=2;

    	if(currency.equals("KRW")||currency.equals("JPY")||currency.equals("")){
    		nPointPosCnt = 0;
    	}else if(currency.equals("JOD")){
    		nPointPosCnt = 3;
    	}else{
    		nPointPosCnt = 2;
    	}
   	
        return StringUtil2.formatCurrency(amount, nPointPosCnt);
    }    
    
    // 수정
    public static String formatCurrency(String amount)
    {
    	int nPointPosCnt = Formatter2.DEF_CURRENCY_POINT_POS;
    	/*
    	String sAmt = amount;
    	int nPos = sAmt.lastIndexOf(".");
    	if(nPos > 0)
    	{
    		nPointPosCnt = sAmt.length() - nPos - 1;
    	}
    	if(nPointPosCnt <= 0)
    	{
    		nPointPosCnt = Formatter2.DEF_CURRENCY_POINT_POS;
    	}
    	*/
        return Formatter2.currency(amount, nPointPosCnt);
    }

    // 추가. 소수점 뒷자리수를 받는 메소드 추가.
    public static String currency(int amount, int nPointPosCnt)
    {
    	return StringUtil2.formatCurrency(amount, nPointPosCnt);
    }
    public static String currency(int amount)
    {
    	return Formatter2.currency(amount, Formatter2.DEF_CURRENCY_POINT_POS);
    }
    
    // 추가. 소수점 뒷자리수를 받는 메소드 추가.
    public static String formatCurrency(int amount, int nPointPosCnt)
    {
        return StringUtil2.formatCurrency(amount, nPointPosCnt);
    }
    // 수정
    public static String formatCurrency(int amount)
    {
    	int nPointPosCnt = Formatter2.DEF_CURRENCY_POINT_POS;
    	/*
    	String sAmt = Integer.toString(amount);
    	int nPos = sAmt.lastIndexOf(".");
    	if(nPos > 0)
    	{
    		nPointPosCnt = sAmt.length() - nPos - 1;
    	}
    	if(nPointPosCnt <= 0)
    	{
    		nPointPosCnt = Formatter2.DEF_CURRENCY_POINT_POS;
    	}
    	*/
    	
        return Formatter2.currency(amount, nPointPosCnt);
    }
    
    // 추가. 소수점 뒷자리수를 받는 메소드 추가.
    public static String currency(double amount, int nPointPosCnt)
    {
    	return StringUtil2.formatCurrency(amount, nPointPosCnt);
    }
    public static String currency(double amount)
    {
    	return Formatter2.currency(amount, Formatter2.DEF_CURRENCY_POINT_POS);
    }
    
    // 추가. 소수점 뒷자리수를 받는 메소드 추가.
    public static String formatCurrency(double amount, int nPointPosCnt)
    {
        return StringUtil2.formatCurrency(amount, nPointPosCnt);
    }
    // 수정
    public static String formatCurrency(double amount)
    {
    	int nPointPosCnt = Formatter2.DEF_CURRENCY_POINT_POS;
    	/*
    	String sAmt = Double.toString(amount);
    	int nPos = sAmt.lastIndexOf(".");
    	if(nPos > 0)
    	{
    		nPointPosCnt = sAmt.length() - nPos - 1;
    	}
    	if(nPointPosCnt <= 0)
    	{
    		nPointPosCnt = Formatter2.DEF_CURRENCY_POINT_POS;
    	}
    	*/
    	
        return Formatter2.currency(amount, nPointPosCnt);	//Formatter2.DEF_CURRENCY_POINT_POS);
    }
    
    // 추가. 문자열을 숫자로 변환 -2010.09.15 한지훈
    public static String extract_numeral(String str)
    {
      String numeral = "", temp = "";
      if ( str == null )
      {
        numeral = null;
        }
      else 
      {
          for( int i = 0; i < str.length(); i++ )
          {
                  temp = str.substring(i,i+1);
                  if( (temp.charAt(0)>47 && temp.charAt(0)<58) || temp.charAt(0) == 46) //아스키 코드값으로 비교
                  {
                  numeral += temp;
                  }
           }
         }
//    null값일 경우 0을 대입 -2010.10.01 한지훈
      if ( numeral == "" )
      {
      	numeral = "0";
      }
       return numeral;
    } 
     
    /*
    public static String currency(String amount)
    {
        return StringUtil.formatCurrency(amount);			
    }

    public static String formatCurrency(String amount)
    {
        return StringUtil.formatCurrency(amount);
    }

    public static String currency(int amount)
    {
        return StringUtil.formatCurrency(amount);
    }

    public static String formatCurrency(int amount)
    {
        return StringUtil.formatCurrency(amount);
    }

    public static String currency(double amount)
    {
        return StringUtil.formatCurrency(amount);
    }

    public static String formatCurrency(double amount)
    {
        return StringUtil.formatCurrency(amount);
    }
    */

    public static String formatQty(String qty)
    {
        try
        {
            return NumberFormatter.formatQty(qty);
        }
        catch(Exception e)
        {
            return "";
        }
    }

    public static String formatQty(int qty)
    {
        return formatQty(String.valueOf(qty));
    }

    public static String formatQty(long qty)
    {
        return formatQty(String.valueOf(qty));
    }

    public static String formatQty(double qty)
    {
        return formatQty(String.valueOf(qty));
    }

    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());
    }

    public static String PATTERN_0 = WAFConfig.get("waf.formatter.date.PATTERN_0", "yyyyMMdd");
    public static String PATTERN_1 = WAFConfig.get("waf.formatter.date.PATTERN_1", "yyyy/MM/dd");
    public static String PATTERN_2 = WAFConfig.get("waf.formatter.date.PATTERN_2", "yyyy/MM/dd HH:mm:ss");
    public static String PATTERN_3 = WAFConfig.get("waf.formatter.date.PATTERN_3", "yyyy-MM-dd HH:mm:ss.S");
    
    /**
     * 2010.10.07 소수점 이하 절삭한다.
     * @param orgVal
     * @return
     */
    public static String getCutPointKrw(String orgVal)
    {
    	String	chgVal		= (new BigDecimal(orgVal)).toString();

		try
		{
			if(chgVal.lastIndexOf(".") >= 0)
			{
				return chgVal.substring(0, chgVal.lastIndexOf("."));
			}
			else
			{
				return chgVal;
			}
		} catch(Exception e)
		{
			System.out.print(e.getMessage());
			return chgVal;
		}
    }
    /**
     * 2010.10.07. 외화인 경우 넘겨받은 자리수로 절사한다.
     * @param orgVal
     * @return
     */
    public static String getCutPointForeignCurrency(String orgVal, String cur_len)
    {
    	int		POS_CUR_DELIM	= 2;
    	String 	strOrg 			= (new BigDecimal(orgVal)).toString();
//		int		pointPos		= -1;

		try
		{
			if(Integer.parseInt(cur_len) > 0)
			{
				POS_CUR_DELIM	= Integer.parseInt(cur_len);
			}
			
			if(strOrg.lastIndexOf(".") >= 0)
			{
				if(strOrg.length() - (strOrg.lastIndexOf(".") + 1) <= POS_CUR_DELIM)
				{
					// 해당 소수점 길이보다 이하이다. 원래값 return 한다.
					return orgVal;
				}
				else
				{
					return strOrg.substring(0, strOrg.lastIndexOf(".") + 1 + POS_CUR_DELIM);
				}
			}
			else
			{
				return orgVal;
			}
		} catch(Exception e)
		{
			System.out.print(e.getMessage());
			return orgVal;
		}
    }

}