package nlib.sch.util;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.psl.dataaccess.util.EgovMap;
 

/**
 * <pre>
 * @Class Name : NlibCmmUtil.java
 * 
 * @Description : Nlib 공통유틸
 * 
 * 
 * @프로젝트명: 지방문화원 통합자료관리시스템 구축사업 (2021)
 *
 * </pre>
 *
 * @ ------------    --------    ---------------------------
 * @ 수정일                     수정자             수정내용
 * @ ------------    --------    ---------------------------
 * @ 2021. 7. 21.    JSYOO       최초 생성
 *
 * 
 * @author 이씨플라자 * DIGITALSHIP JSYOO
 * @since 2021. 7. 21.
 * @version 1.0
 *
 */
@Component
public class NlibCmmUtil {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(NlibCmmUtil.class);
	public static String DEFAULT_DELIMITER = "-";
	protected static EgovPropertyService propertyService;

	@Resource(name = "propertiesService")
	private EgovPropertyService propertyServiceInstance;
	
	@PostConstruct
	private void init() {
		propertyService = propertyServiceInstance;
	}
	public static String reflectionToString(Object obj) {
		return ToStringBuilder.reflectionToString(obj);
	}
	
	public static String clearXSS(String value) {
		if (value == null || value.trim().equals("")) {
			return "";
		}
		String returnValue = value;
		returnValue = returnValue.replaceAll("&", "&amp;");
		returnValue = returnValue.replaceAll("<", "&lt;");
		returnValue = returnValue.replaceAll(">", "&gt;");
		returnValue = returnValue.replaceAll("'", "&#39;");
		returnValue = returnValue.replaceAll("eval\\((.*)\\)", "");
		returnValue = returnValue.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
		returnValue = returnValue.replaceAll("\"", "&quot;");
		returnValue = returnValue.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;");
		returnValue = returnValue.replaceAll("script", "");
		returnValue = returnValue.replaceAll("alert", "");
		return returnValue;
	}
	
	public static String escapeNewlineToBr(String text) {
		String str = text;
		if (StringUtils.isEmpty(str)) return str;
		
		if (str.indexOf("\\r") >= 0) str = str.replaceAll("\\\\r", "\r");
		if (str.indexOf("\\n") >= 0) str = str.replaceAll("\\\\n", "\n");
		if (str.indexOf("\r\n") >= 0 || str.indexOf("\n") >= 0 || str.indexOf("\r") >= 0) {
			str = str.replaceAll("\\r\\n", "<br/>");
			str = str.replaceAll("\\r", "<br/>");
			str = str.replaceAll("\\n", "<br/>");
		}
		return str;
	}
	public static String escapeNewlineToSpace(String text) {
		String str = text;
		if (StringUtils.isEmpty(str)) return str;
		if (str.indexOf("\\r") >= 0) str = str.replaceAll("\\\\r", "\r");
		if (str.indexOf("\\n") >= 0) str = str.replaceAll("\\\\n", "\n");
		if (str.indexOf("\r\n") >= 0 || str.indexOf("\n") >= 0 || str.indexOf("\r") >= 0) {
			str = str.replaceAll("\\r\\n", "");
			str = str.replaceAll("\\r", "");
			str = str.replaceAll("\\n", "");
		}
		str = str.replaceAll("\"", "");
		str = str.replaceAll("'", "");
		return str;
	}
	public static String cut(String text, int size) {
		return cut(text, size, "");
	}
	public static String cut(String text, int size, String suffix) {
		if (text == null) {
		return "";
		}
		if (text.length() < size) {
		return text;
		}
		size = size - suffix.length();
		return StringUtils.substring(text, 0, size) + suffix;
	}
	public static boolean isConsecutive(String str, int n) {
		int sumOfDifferences = 0;
		int lastTemp = 0;
		Boolean consecutive = false;
		for (int i = 0; i < str.length() - 1; i++) {
		  int temp = str.charAt(i) - str.charAt(i + 1);
		  if (temp != lastTemp) {
		    sumOfDifferences = 0;
		  }
		  if (temp == 1 || temp == -1) {
		    sumOfDifferences += temp;
		  } else {
		    sumOfDifferences = 0;
		  }
		  if (sumOfDifferences == n - 1 || sumOfDifferences == ((n - 1) * -1)) {
		    consecutive = true;
		    break;
		  }
		  lastTemp = temp;
		}
		return consecutive;
	}
	public static boolean regexFind(String str, String regex) {
	    Pattern pattern = Pattern.compile(regex);
	    Matcher matcher = pattern.matcher(str);
	    return matcher.find();
	}
	public static String getIpAddress(HttpServletRequest req) {
		String ipAddress = "";
		if (req.getHeader("X-Forwarded-For") == null) {
		  ipAddress = req.getRemoteAddr();
		} else {
		  ipAddress = req.getHeader("X-Forwarded-For");
		  int idx = ipAddress.indexOf(',');
		  if (idx > -1) {
		    ipAddress = ipAddress.substring(0, idx);
		  }
		}
		return ipAddress;
	}
	
	public static String getUrl(HttpServletRequest req, String domain) {
	    final String uri = req.getRequestURI();
	    final String queryString = req.getQueryString();
	    String url = "";
		url = domain + uri;
		if (StringUtils.isNotBlank(queryString)) {
			url += "?" + queryString;
	    }
	    return url;
	}
	public static int getTridentVersion(String userAgent) {
	    String lowerUserAgent = userAgent.toLowerCase();
	    int start = lowerUserAgent.indexOf("trident/");
	    if (start == -1) {
	      return 0;
	    }
	    String trident = lowerUserAgent.substring(start + 8, start + 9);
	    return NumberUtils.toInt(trident);
	}
	public static String getPropertyStr(String key) {
		String str = "";
		if (org.apache.commons.lang3.StringUtils.isNotBlank(key)) str = propertyService.getString(key);
		return str;
	}
	public static String deleteChar(String str) {
		if (StringUtils.isEmpty(str)) return str;
		
		String  regExpNumber = "[^0-9]";
		return str.replaceAll(regExpNumber, "");
	}
	@SuppressWarnings("rawtypes")
	public static boolean isEmpty(Map map, String key) {
		boolean isEmpty = true;
		if (map == null) return isEmpty;

		Object obj = map.get(key);
		if ( obj != null 
				&& !StringUtils.isEmpty(obj.toString())
				&& !(obj+"").equals("null")) {
			
			isEmpty = false;
		}
		return isEmpty;
	}
	public static String[] getValueArr(List<EgovMap> list, String key) {
		String[] exidArr = null;
		if (list == null || list.size() == 0) return exidArr;
		exidArr = new String[list.size()];
		for (int i=0; i<list.size(); i++) {
			EgovMap data = list.get(i);
			String exid = getStr(data, key);
			exidArr[i] = exid;
		}
		return exidArr;
	}
    public static String[] splitStr(String splittee, String splitChar){
        String taRetVal[] = null;
        StringTokenizer toTokenizer = null;
        int tnTokenCnt = 0;
        try {
            toTokenizer = new StringTokenizer(splittee, splitChar);
            tnTokenCnt = toTokenizer.countTokens();
            taRetVal = new String[tnTokenCnt];

            for(int i=0; i<tnTokenCnt; i++) {
                if(toTokenizer.hasMoreTokens())	taRetVal[i] = toTokenizer.nextToken();
            }
        } catch (NullPointerException e) {
        	LOGGER.debug("null in splitStr() : array(0)");
        	taRetVal = new String[0];
        } catch (Exception e) {
        	LOGGER.debug("Error in splitStr() : array(0)");
            taRetVal = new String[0];
        }
        return taRetVal ;
    }
	public static String getNumberDashAddFmt(String value01, String value02, String value03) {
		String str = "";
		if( org.apache.commons.lang3.StringUtils.isBlank(value02) || org.apache.commons.lang3.StringUtils.isBlank(value03)){
		}else{
			str = value01 + DEFAULT_DELIMITER + value02 + DEFAULT_DELIMITER + value03;
		}
		return str;
	}
	@SuppressWarnings("rawtypes")
	public static String getStr(Map map, String key) {
		String str = "";
		if (isEmpty(map, key)) return str;
		str = map.get(key)+"";
		return str;
	}
	public static String getIp(HttpServletRequest request)  throws IOException, InvocationTargetException, SQLException, Exception {
		
		String ip = request.getHeader("X-Forwarded-For");
		
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		 
		return ip;
	}
	
}

