package cmm.taglibs;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import cmm.Constant;
import cmm.util.CmmUtil;
import cmm.util.DataMap;
import cmm.util.DateUtil;

//import com.unidocs.cipher.PDFInfoEncrypter; // DDDDDDDDDDDdddd 아직 관련 LIB 받지 못함 (2021.08.13)


public class FunctionTag {
    
    
	static final String DELIMITER = "-";
	public static String toBr(String value) {
		String str = "";
		if( org.apache.commons.lang3.StringUtils.isBlank(value) ){
			return str;
		}
		str = value;
		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 removeTag(String value) {
		String str = "";
		if( org.apache.commons.lang3.StringUtils.isBlank(value) ){
			return str;
		}else{
			str = value.replaceAll("<(/)?([a-zA-Z]*)(\\s[a-zA-Z]*=[^>]*)?(\\s)*(/)?>", "");
		}
		return str;
	}
	
	public static String dateFormatString(String strDate) throws IOException, InvocationTargetException, SQLException {
		String formatDate = "";
		if( StringUtils.isBlank(strDate) ) return formatDate;
		
		String regExpNumber = "^[0-9]*$";
		strDate = strDate.trim();
		
		Pattern p = Pattern.compile(regExpNumber);
		Matcher m = p.matcher(strDate);
		
		if( !m.matches() ) {
			return strDate;
		}
		
		int strDateLen = strDate.length();
		if(strDateLen >= 4) {
			formatDate = strDate.substring(0, 4);
		} 
		if(strDateLen >= 6) {
			formatDate += DELIMITER + strDate.substring(4, 6) ;
		} 
		if(strDateLen >= 8) {
			formatDate += DELIMITER + strDate.substring(6) ;
		}
		
		return formatDate;
	}
	
	
	public static String[] dateSplitArrayString(String strDate, String type) throws IOException, InvocationTargetException, SQLException {
		String formatDate [] = new String[3];
		if( StringUtils.isBlank(strDate) ) return formatDate;
		
		String regExpNumber = "^[0-9]*$";
		String rDate =  strDate.replaceAll("-", "").trim();
		
		Pattern p = Pattern.compile(regExpNumber);
		Matcher m = p.matcher(rDate);
		
		if( !m.matches() ) {
			for(int i=0;i<formatDate.length;i++){
				formatDate[i] = strDate;
			}
			return formatDate;
		}
		
		int strDateLen = rDate.length();
		if(strDateLen >= 4) {
			formatDate[0] = rDate.substring(0, 4);
		} 
		if(strDateLen >= 6) {
			if( "M".equals(type) ){
				if(NumberUtils.toInt(rDate.substring(4, 6)) < 10){
					formatDate[1] =  rDate.substring(5, 6);
				}else{
					formatDate[1] =  rDate.substring(4, 6);
				}
			}else{
				formatDate[1] =  rDate.substring(4, 6);
			}
		} 
		if(strDateLen >= 8) {
			formatDate[2] = rDate.substring(6) ;
		}
		
		return formatDate;
	}
	
	public static String moneyFormatString(String strMoney) throws IOException, InvocationTargetException, SQLException {
		String formatMoney = "";
		if( StringUtils.isBlank(strMoney) ) return formatMoney;
		if( !NumberUtils.isNumber(strMoney) ) return strMoney;
		
		DecimalFormat df = new DecimalFormat("#,###");
		formatMoney = df.format(NumberUtils.toLong(strMoney));
		
		return formatMoney;
	}
	public static long getDday(String start, String end) throws ParseException, IOException, InvocationTargetException, SQLException {
		
		if( StringUtils.isBlank(start) || StringUtils.isBlank(end)){
			return -9999;
		}
		start = start.replaceAll("-", "").trim();
		end = end.replaceAll("-", "").trim();
		if( !NumberUtils.isNumber(start) || !NumberUtils.isNumber(end)){
			return -9999;
		}
		if( start.length() < 8 || end.length() < 8 ){
			return -9999;
		}
		
		DateFormat df = new SimpleDateFormat("yyyyMMdd");
	    Date s =  df.parse(start);
	    Date e =  df.parse(end);
	    
		long diff = e.getTime() - s.getTime();
	    return TimeUnit.MILLISECONDS.toDays(diff);
	}
	
	public static boolean isIn(String to) throws ParseException, IOException, InvocationTargetException, SQLException {
		if( StringUtils.isBlank(to)){
			return false;
		}
		to = to.replaceAll("-", "").replaceAll(".", "").trim();
		if( !NumberUtils.isNumber(to) ){
			return false;
		}
		if( to.length() < 8){
			return false;
		}
		DateFormat df = new SimpleDateFormat("yyyyMMdd");
		Date end  = df.parse(to);
		Date now  = df.parse(df.format(new Date()));
		
		/*if(now.getTime() > end.getTime()){
			return false;
		}else{
			return true;
		}*/
		if(now.getTime() >= end.getTime()){
			return true;
		}else{
			return false;
		}
	}
	public static String getMonth(String target) throws IOException, InvocationTargetException, SQLException {
		String mm = "";
		if( StringUtils.isBlank(target)){
			// 인자값을 빈값으로 보내면 현재월을 넘긴다.
			Calendar cal = Calendar.getInstance();
			mm = String.valueOf(Integer.toString(cal.get(Calendar.MONTH)+1));
		}
		mm = target.replaceAll("-", "").trim();
		if( !NumberUtils.isNumber(mm) ){
			return target;
		}
		if( mm.length() < 2){
			mm = "0"+mm;
		}
		return mm;
	}
	public static String getDay(String target) throws IOException, InvocationTargetException, SQLException {
		String dd = "";
		if( StringUtils.isBlank(target)){
			// 인자값을 빈값으로 보내면 현재일을 넘긴다.
			Calendar cal = Calendar.getInstance();
			dd = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
		}
		dd = target.replaceAll("-", "").trim();
		if( !NumberUtils.isNumber(dd) ){
			return target;
		}
		if( dd.length() < 2){
			dd = "0"+dd;
		}
		return dd;
	}
	
	public static boolean isWeekend(String date_yyyymmdd) throws IOException, InvocationTargetException, SQLException {
		boolean rtnBoolean = false;
		if( !StringUtils.isBlank(date_yyyymmdd) ){
			String date=date_yyyymmdd.replaceAll("-", "").trim();
			if(date.length() >= 8 && NumberUtils.isNumber(date) ){
				int year = Integer.parseInt(date.substring(0,4));
		        int month = Integer.parseInt(date.substring(4,6));
		        int day = Integer.parseInt(date.substring(6,8));
		        Calendar cal = Calendar.getInstance();
		        cal.set(year, month-1, day );
		        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
		        if( dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY){
		        	// 주말
		        	rtnBoolean = true;
		        }
			}
		}
		return rtnBoolean;
	}
	public static String getToDay() throws Exception {
		return DateUtil.getDateString(new Date(),  new SimpleDateFormat("yyyy-MM-dd", Locale.KOREA));
	}
	public static String getToDay2() throws Exception {
		return DateUtil.getDateString(new Date(),  new SimpleDateFormat("yyyyMMdd", Locale.KOREA));
	}
	public static String reverseSido(String sido){
		if(sido == null || "".equals(sido)) return "";
		String rtnSido = "";
		for(int i=0; i<Constant.AIS_SIDO_NAME_ARRAY.length;i++){
			if(sido.indexOf( Constant.AIS_SIDO_NAME_ARRAY[i] ) > -1 ){
				rtnSido = Constant.AIS_SIDO_NAME_ARRAY[i];
				break;
			}
			if(sido.indexOf( Constant.AIS_SIDO_PARAM_NAME_ARRAY[i] ) > -1 ){
				rtnSido = Constant.AIS_SIDO_NAME_ARRAY[i];
				break;
			}
		}
		return rtnSido;
	}
	public static boolean isAreaOfInterest(String sido, String sigungu , DataMap pscHst){
		boolean rtnBoolean = false;
		if(sido == null || "".equals(sido)) return rtnBoolean;
		if(sigungu == null || "".equals(sigungu)) return rtnBoolean;
		
		if(pscHst == null) return rtnBoolean;
		
		DataMap pscHst1 = (DataMap) pscHst.get("pscHst1");
		DataMap pscHst2 = (DataMap) pscHst.get("pscHst2");
		DataMap pscHst3 = (DataMap) pscHst.get("pscHst3");
		
		if(sido.trim().equals(pscHst1.getString("sidoName").trim()) && sigungu.trim().equals(pscHst1.getString("sigunguName").trim())){
			rtnBoolean = true;
		}
		if(sido.trim().equals(pscHst2.getString("sidoName").trim()) && sigungu.trim().equals(pscHst2.getString("sigunguName").trim())){
			rtnBoolean = true;
		}
		if(sido.trim().equals(pscHst3.getString("sidoName").trim()) && sigungu.trim().equals(pscHst3.getString("sigunguName").trim())){
			rtnBoolean = true;
		}
		return rtnBoolean;
	}
	
	
	//unidocs Viewer
	public static String unidocsViewer(String filePath, String fileNm) throws Exception {
		//String path = "/apps/ezpdfwebviewer/WEB-INF/ezPDFWebViewer/releasecontents/sokcho_20180608.pdf"; 
		//String path = "/nfs/kccf_doc/cfba8b83e460323079b67be17ba6f96d.pdf";
		String path = filePath + fileNm;
	  	String download = "false";
	    String print = "false";
	    String annotation = "false";
	 	String[] param = new String[]{ java.net.URLEncoder.encode( path, "UTF-8" ), download, print, annotation};
//	    String encData = PDFInfoEncrypter.encrypt( param );  
//		return encData;
	 	return null; // DDDDDDDDDDDdddd 아직 관련 LIB 받지 못함 (2021.08.13)
	}
	
	/**
	 * ASSET 이미지 URL
	 * jsp 파일에서 다음과 같이 사용하던 linkUrl 로직을 포함함
	 * 
<c:set var="linkUrl" value="${amsAssetsPath}${amsThumbnailPath}"/>
<c:if test="${fn:contains(resultInfo.mainImg, '/' )}"><c:set var="linkUrl" value="${amsAssetsPath}"/></c:if>
	 * 
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public static String assetImgUrl(String filePath) throws Exception {
		String url = "";
		if (StringUtils.isEmpty(filePath)) return url;

		String amsAssetsPath = CmmUtil.getPropertyStr(Constant.AMS_SERVER_KEY) + CmmUtil.getPropertyStr(Constant.AMS_ASSETS_PATH_KEY);
		String amsThumbnailPath = CmmUtil.getPropertyStr(Constant.AMS_THUMBNAIL_PATH_KEY);

		if (filePath.startsWith("http")) { // http 포함한 전체 경로일 경우 ex) object storage 이미지
			url = filePath;
			
		} else if (filePath.indexOf("/") >= 0) { // ex) 2/2/7292_thumbnail.jpg
			url = amsAssetsPath + "/" + filePath;
			
		} else {
			url = amsAssetsPath + "/" + amsThumbnailPath + "/" + filePath; // ex) ac6be22ee9db4414aeb4dab6078d27feb723f1c0.jpg
		}
		
		url = url.replaceAll("//", "/");
		url = url.replaceAll(":/", "://"); // ex) https:/ => https://
		
		return url;
	}
	
	/**
	 * 업로드 이미지 URL
	 * 
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public static String uploadImgUrl(String filePath) throws Exception {
		String url = "";
		if (StringUtils.isEmpty(filePath)) return url;

		// 로컬 개발 시 개발서버 upload 하위 이미지를 바라보도록 설정, 운영에서는 운영 upload 폴더 바라봄
		String uploadHomePath = CmmUtil.getPropertyStr(Constant.UPLOAD_HOME_KEY);

		if (filePath.startsWith("/upload")) { // ex) /upload/post/20180921142754.png (포스트, 배너 등)
			url = uploadHomePath + "/" + filePath;
			
		} else {
			url = filePath;
		}
		
		url = url.replaceAll("//", "/");
		url = url.replaceAll(":/", "://"); // ex) https:/ => https://
		
		return url;
	}
	
	/**
	 * 두개의 문자열을 delimiter로 연결하여 반환
	 * 
	 * ex)	*, aaa, bbb	=> aaa*bbb
	 *   	*, aaa		=> aaa
	 *   	*, "", bbb	=> bbb
	 *   	*, "", ""	=> ""
	 *   
	 * @param delimiter
	 * @param str1
	 * @param str2
	 * @return
	 * @throws Exception
	 */
	public static String joinWithDelimiter(String delimiter, String str1, String str2) throws Exception {
		String result = "";
		
		if (StringUtils.isEmpty(str1) && StringUtils.isEmpty(str2)) return result;
		result = str1;
		if (StringUtils.isNotEmpty(str1) && StringUtils.isNotEmpty(str2)) result += delimiter;
		result += str2;
		
		return result;
	}
	
}
