package com.munjaon.client.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public final class CommonUtil {
    public static final String DATE_FORMAT_14 = "yyyyMMddHHmmss";
    public static final int TIMEOUT_DIVIDE = 1000 * 60;

    // NewLine 공백처리하기
    public static String cutNewLine(String msg){
        String encString = "";
        if(msg != null){
            encString = msg.replaceAll("\r", "");
            encString = encString.replaceAll("\n", "");
        }
        return encString;
    }
    // NewLine 인코딩 돌리기
    public static String encodeNewLine(String msg){
        String encString = "";
        if(msg != null){
			/*encString = msg.replaceAll("\r", "\n");
			encString = encString.replaceAll("\n\n", "\n");
			encString = encString.replaceAll("\n", "ⓝⓛ");*/
            encString = msg.replaceAll("\r", "");
            encString = encString.replaceAll("\n", "ⓝⓛ");
        }
        return encString;
    }
    // NewLine 디코딩 돌리기
    public static String decodeNewLine(String msg){
        String encString = "";
        if(msg != null){
            encString = msg.replaceAll("ⓝⓛ", "\n");
        }
        return encString;
    }
    // Comma 인코딩 돌리기
    public static String encodeComma(String msg){
        String encString = "";
        if(msg != null){
            encString = msg.replaceAll("\"", "ⓒⓞⓜⓜⓐ");
        }
        return encString;
    }
    // Comma 디코딩 돌리기
    public static String decodeComma(String msg){
        String decString = "";
        if(msg != null){
            decString = msg.replaceAll("ⓒⓞⓜⓜⓐ", "\"");
        }
        return decString;
    }
    // 문자열이 널인지 체크하는 함수
    public static boolean checkMsgNull(String msgStr){
        boolean isValid = false;
        String[] msgArray = msgStr.split("ⓜⓢ");
        int msgArrayLen = msgArray.length;
        for(int i=0;i<msgArrayLen;i++){
            msgArray[i] = msgArray[i].trim();
            if(msgArray[i].length() < 1){
                isValid = true;
                break;
            }
        }
        return isValid;
    }
    // 해당 길이만큼 문자열을 자르는 함수
    public static String cutString(String str, int limit)
    {
        int len = str.length();
        int sumLength=0;
        String cutString = null;
        byte[] toByte = str.getBytes();

        if(limit < 2)
            return "";
        if(toByte.length > limit){
            for(int cnt = 0 ; cnt < len ;cnt++){
                if ((str.charAt(cnt) & 0xFF00) == 0) // 1 Byte 문자이면
                    sumLength++;
                else // 2바이트 문자라면...
                    sumLength = sumLength + 2;
                if(sumLength > limit){
                    cutString = str.substring(0, cnt);
                    break;
                }
            }
        }else{
            cutString = str;
        }

        return cutString;
    }
    // 날짜를 구간별로 자르는 함수
    // (inDate:날짜 >> (입력형식:2012년 12월 20일일 경우 : 20121220))
    public static int substringDate(String inDate, int beginIndex, int lastIndex){
        int subDate = -1;
        inDate = doNumber(inDate);
        if(inDate.length() == 8){
            if((beginIndex < lastIndex) && (lastIndex <= 8))
                subDate = Integer.parseInt(inDate.substring(beginIndex, lastIndex));
        }
        return subDate;
    }
    // 시간을 구간별로 자르는 함수
    public static int substringTime(String inTime, int beginIndex, int lastIndex){
        int subDate = -1;
        inTime = doNumber(inTime);
        if(inTime.length() == 6){
            if((beginIndex < lastIndex) && (lastIndex <= 6))
                subDate = Integer.parseInt(inTime.substring(beginIndex, lastIndex));
        }
        return subDate;
    }
    public static boolean validDate(String fullDate){
        boolean validFlag = true;
        fullDate = doNumber(fullDate);

        if(fullDate.length() != 14){
            validFlag = false;
        }else{
            if(!(isValidDay(fullDate.substring(0, 8)) && isValidTime(fullDate.substring(8, 14))))
                validFlag = false;
        }
        return validFlag;
    }
    // 유효한 날짜 형식인지 체크하는 함수
    public static boolean isValidDay(String inDate){
        boolean validFlag = true;
        int year = substringDate(inDate, 0, 4);
        // 년도에서 앞에 두자리 체크
        if(year < 2013){
            validFlag = false;
        }
        int month = substringDate(inDate, 4, 6);
        int day = substringDate(inDate, 6, 8);
        if (month < 1 || month > 12) { // check month range
            validFlag = false;
        }
        if (day < 1 || day > 31) {
            validFlag = false;
        }
        if ((month==4 || month==6 || month==9 || month==11) && day==31) {
            validFlag = false;
        }
        if (month == 2) { // check for february 29th
            boolean isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
            if (day>29 || (day==29 && !isleap)) {
                validFlag = false;
            }
        }
        return validFlag;
    }
    // 유효한 날짜 형식인지 체크하는 함수
    public static boolean isValidTime(String inTime){
        boolean validFlag = true;
        int hour = substringTime(inTime, 0, 2);
        int minute = substringTime(inTime, 2, 4);
        int second = substringTime(inTime, 4, 6);
        if(hour < 0 || hour > 23)
            validFlag = false;
        if(minute < 0 || minute > 59)
            validFlag = false;
        if(second < 0 || second > 59)
            validFlag = false;
        return validFlag;
    }
    // 예약일이 하루전인지 체크하는 함수
    // 앞의 날짜가 뒤의 날짜보다 이전이면: true / 그렇지않으면 false)
    public static boolean isBeforeDate(String srcDate, String destDate){
        boolean validFlag = false;
        Calendar srcCal = getCalendar(srcDate);
        Calendar destCal = getCalendar(destDate);
        if(srcCal == null || destCal == null){
            validFlag = true;
        }else{
            if(srcCal.before(destCal))
                validFlag = true;
        }

        return validFlag;
    }

    public static Calendar getCalendar(int hour){
        Calendar thisCal = null;
        thisCal.add(Calendar.HOUR, hour);
        return thisCal;
    }
    public static Calendar getCalendar(String inDate){
        Calendar thisCal = null;
        inDate = doNumber(inDate);
        if(inDate.length() == 14 && validDate(inDate)){
            String date = inDate.substring(0, 8);
            String time = inDate.substring(8, 14);
            int year = substringDate(date, 0, 4);
            int month = substringDate(date, 4, 6);
            int day = substringDate(date, 6, 8);
            int hour = substringTime(time, 0, 2);
            int minute = substringTime(time, 2, 4);
            int second = substringTime(time, 4, 6);
            thisCal = Calendar.getInstance();
            thisCal.set(year, (month-1), day, hour, minute, second);
        }
        return thisCal;
    }
    public static String currentTime(){
        Calendar currDate = Calendar.getInstance();
        SimpleDateFormat dateForm = new SimpleDateFormat("HHmmss");
        return dateForm.format(currDate.getTime());
    }
    public static String getLastDate(String year, String month, String day){
        String dateStr = null;
        String lastDay = null;
        Calendar currDate = Calendar.getInstance();
        currDate.set(Integer.parseInt(year),Integer.parseInt(month)-1,Integer.parseInt(day));
        lastDay = Integer.toString(currDate.getActualMaximum(Calendar.DAY_OF_MONTH));
        dateStr = year+month+lastDay;
        return dateStr;
    }
    public static String currentDay(){
        Calendar currDate = Calendar.getInstance();
        SimpleDateFormat dateForm = new SimpleDateFormat("yyyyMMdd");
        return dateForm.format(currDate.getTime());
    }
    public static String currentDate(){
        Calendar currDate = Calendar.getInstance();
        SimpleDateFormat dateForm = new SimpleDateFormat("yyyyMMddHHmmss");
        return dateForm.format(currDate.getTime());
    }
    public static String currentLogDate(){
        Calendar currDate = Calendar.getInstance();
        SimpleDateFormat dateForm = new SimpleDateFormat("[yyyy-MM-dd][HH:mm:ss]");
        return dateForm.format(currDate.getTime());
    }
    // "yyyyMMddHHmmss" 의 조합
    public static String formatDate(String format){
        Calendar currDate = Calendar.getInstance();
        SimpleDateFormat dateForm = new SimpleDateFormat(format);
        return dateForm.format(currDate.getTime());
    }
    public static String getTargetDate(int term){
        Calendar currDate = Calendar.getInstance();
        currDate.add(Calendar.HOUR, term);
        SimpleDateFormat dateForm = new SimpleDateFormat("yyyyMMddHHmmss");
        return dateForm.format(currDate.getTime());
    }
    public static String getTargetDay(int term){
        Calendar currDate = Calendar.getInstance();
        currDate.add(Calendar.HOUR, term);
        SimpleDateFormat dateForm = new SimpleDateFormat("yyyyMMdd");
        return dateForm.format(currDate.getTime());
    }
    public static Date parseDate14(String sDay){
        Date date = null;
        if(sDay != null || sDay.length() == 14){
            SimpleDateFormat dateForm = new SimpleDateFormat(DATE_FORMAT_14);
            try {
                date = dateForm.parse(sDay);
            } catch (ParseException e) {

            }
        }

        return date;
    }
    public static int validTimeOut(String sDay){
        int interval = 100000;
        Date fromDate = parseDate14(sDay);
        Date toDate = parseDate14(currentDate());
        if(fromDate != null && toDate != null){
            long duration = toDate.getTime() - fromDate.getTime();
            interval = (int)(duration / TIMEOUT_DIVIDE);
        }

        return interval;
    }
    // 숫자만 반환하는 함수
    public static String doNumber(String spell){
        String phoneNumber = "";
        if(spell == null){
            return phoneNumber;
        }
        spell = spell.trim();
        int spell_Length = spell.length();
        if(spell_Length < 1){
            return phoneNumber;
        }
        for(int i=0;i<spell_Length;i++){
            char eachChar = spell.charAt(i);
            if( 0x30 <= eachChar && eachChar <= 0x39 ){
                phoneNumber += eachChar;
            }
        }
        return phoneNumber;
    }
    // 소수점 뒤에 해당하는 자리만큼 자르기
    public static String cutFloatNumber(String srcNum, int digit){
        String headNum = "";
        String tailNum = "";
        String retNum = "";

        if(!(srcNum == null || srcNum.trim().equals(""))){
            srcNum = srcNum.trim();
            int index = srcNum.indexOf(".");
            // 소수점 위치가 0보다 큰경우만 처리
            if(index > 0){
                headNum = srcNum.substring(0, index);
                tailNum = srcNum.substring((index + 1), srcNum.length());

                if(tailNum.length() == 0){
                    tailNum = "0";
                }
                if(tailNum.length() > digit){
                    tailNum = tailNum.substring(0, digit);
                }
                retNum = headNum + "." + tailNum;
            }
        }

        return retNum;
    }
    // 수신번호 체크하기
    public static boolean CheckPhone(String src) {
        if(src == null || src.trim().length() < 10) {
            return false;
        }

        if(!src.startsWith("0")) {
            return false;
        }

        return true;
    }
    // 문자열 공백 제거
    public static String trim(String obj) {
        return StringUtil.trim(obj);
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //System.out.println(QueueUtil.cutFloatNumber("10.2", 2));
        //System.out.println(QueueUtil.isValidTime("20131207173555"));

		/*Calendar currDate = Calendar.getInstance();
		currDate.add(Calendar.HOUR, 0); // 1년후의 시간
		System.out.println("하루전 시간 : " + currDate.getTime());*/
        System.out.println(CommonUtil.isBeforeDate("20131206121212", "20131207121212"));
        System.out.println("하루전 : " + CommonUtil.getTargetDay(-24));
        System.out.println(CommonUtil.currentLogDate());
        //Date date = MessageUtil.parseDate14("20141208125958");
        System.out.println("validTimeOut() : " + CommonUtil.validTimeOut("20141209154558"));
    }
}
