package com.handong.smartservice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.handong.smartservice.component.UserInfo;

import io.jsonwebtoken.Claims;

//import com.handong.smartservice.model.OperatingHistoryModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;



@Configuration
public class _AG {
	static public String MEDIA_UPLOAD_LOCAL_PATH;

	//@Value("${app-global.upload-file-path}")
	void setMEDIA_UPLOAD_LOCAL_PATH(String str) {
		MEDIA_UPLOAD_LOCAL_PATH = str;
	}

	public static String getCurrentDateTime() {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.KOREA);
		Date date = new Date();
		return simpleDateFormat.format(date);
	}

	// Timestamp to yyyy-MM-dd HH:mm:ss
	public static String timestampToStr(Object timestamp) {
		if (timestamp == null)
			return "";
		String str = timestamp.toString();
		return str.substring(0, str.length() - 2);
	}

	static public boolean hasText(String str) {
		if (str == null || str.isEmpty())
			return false;

		return true;
	}

	static public String safeStr(String str) {
		if (str == null || str.isEmpty())
			return "";

		return str;
	}

	static public Long toLong(String str) {
		if (str == null || str.isEmpty())
			return 0L;

		return Long.parseLong(str);
	}

	static public Long toLongOrNull(String str) {
		if (str == null || str.isEmpty())
			return null;

		return Long.parseLong(str);
	}

	static public Long toLong(Integer obj) {
		if (obj == null)
			return 0L;

		return obj.longValue();
	}

	static public Long toLong(BigInteger obj) {
		if (obj == null)
			return 0L;

		return obj.longValue();
	}

	static public Boolean toBoolean(String str) {
		if (str == null || str.isEmpty())
			return false;

		return Boolean.parseBoolean(str);
	}

	static public String mapToJson(Map<String, Object> map) {
		String json = "{}";
		ObjectMapper mapper = new ObjectMapper();
		try {
			//json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(data);
			json = mapper.writeValueAsString(map);
		}
		catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		return json;
	}

	static public String mapToJson2(Map<String, String> map) {
		String json = "{}";
		ObjectMapper mapper = new ObjectMapper();
		try {
			//json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(data);
			json = mapper.writeValueAsString(map);
		}
		catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		return json;
	}

	static public String saveUploadedFile(MultipartFile[] attached_files, String strFileName) {
		Date today = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
		dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Seoul"));

		String strSaveFileName = dateFormat.format(today) + "_" + strFileName;

		try {
			File file = new File(_AG.MEDIA_UPLOAD_LOCAL_PATH + strSaveFileName);
			attached_files[0].transferTo(file);
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return strSaveFileName;
	}

    static public Long getNumberFromQuery(String strColName, List<Map<String, Object>> qeuryResult) {
		if (qeuryResult == null || qeuryResult.size() == 0)
			return 0L;
		
		return (Long)qeuryResult.get(0).get(strColName);
	}
	
	static public String getIpAddr(HttpServletRequest request) {
		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.getHeader("X-Real-IP"); 
        }
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
            ip = request.getHeader("X-RealIP"); 
        }
        if (ip ==  null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
            ip = request.getHeader("REMOTE_ADDR");
        }
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip != null && !ip.isEmpty()) {
			ip = ip.split(",")[0].trim();
		}
		return ip;
	}

	//static public void addHistory(EntityManager entityManager, int nType, String strAction, String gid) {
	//	OperatingHistoryModel operatingHistoryModel = new OperatingHistoryModel(entityManager);
	//	operatingHistoryModel.addOperatingHistory(nType, strAction, gid);
	//}

	//JWT Auth
	static public boolean isSkipAuthUri(String uri) {
		if (uri.compareTo("/api/miss-slot.do") == 0 ||
			uri.compareTo("/api/terminal-state.do") == 0 ||
			uri.compareTo("/api/sign-in.do") == 0 ||
            uri.compareTo("/api/sval2.do") == 0 ||
			uri.compareTo("/api/add-transaction.do") == 0) {
            return true;
        }

		return false;
	}

	static public UserInfo createJwtUserInfo(Claims claims) {
		UserInfo principal = new UserInfo(
			Long.parseLong(claims.getSubject()),
			claims.get("user_id", String.class),
			claims.get("nick_name", String.class),
			claims.get("permission", Number.class),
			claims.get("biz_group_id", Number.class)
		);
		return principal;
	}

	static public Map<String, Object> createUserInfoMap(String user_id, String nick_name, Long permission, Long biz_group_id) {
		Map<String, Object> map = new HashMap<>();
		map.put("user_id", user_id);
		map.put("nick_name", nick_name);
		map.put("permission", permission);
		map.put("biz_group_id", biz_group_id);
		return map;
	}
	//

	// 사업자 번호 하이픈 자동추가
	static public String formatBusinessNumber(String input) {
        String digits = input.replaceAll("\\D", "");

        if (digits.length() > 10) {
            digits = digits.substring(0, 10);
        }

        return digits.replaceFirst("^(\\d{3})(\\d{2})(\\d{5})$", "$1-$2-$3");
    }

	// 사업자번호 검증
	static public boolean isValidBusinessNumber(String input) {
		//return true;	//TestCode

        String digits = input.replaceAll("\\D", "");
        if (digits.length() != 10) {
            return false;
        }

        int[] weights = {1, 3, 7, 1, 3, 7, 1, 3, 5};
        int sum = 0;

        for (int i = 0; i < 9; i++) {
            int num = Character.getNumericValue(digits.charAt(i));
            sum += num * weights[i];
        }

        sum += (Character.getNumericValue(digits.charAt(8)) * 5) / 10;

        int checkDigit = (10 - (sum % 10)) % 10;
        return checkDigit == Character.getNumericValue(digits.charAt(9));
    }
}
