package com.eactive.eai.custom.adapter.http.util;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.eactive.eai.util.CryptoUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class VirtualAccountBatchUtil {
	private ObjectMapper mapper = new ObjectMapper();

	public String getGzipValue(String jsonString, String path) {
		try {
			JsonNode rootNode = mapper.readTree(jsonString);
			JsonNode childNode = rootNode.get(path);
			String gzippedValue = childNode.asText();
			return gzippedValue;
		}
		catch(Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
	
	// AZZ22-%d{yyyyMMdd}-%d{hhmmss}.enc -> AZZ22-20240924-093257.enc
	public static String updateDatePattern(String patterm) {
		String str[] = patterm.split("%d");
		String converted = "";
		for(int i=0; i<str.length; i++){
			if(i<1){
				converted = str[i];
			}else{
				String newMsg = "%d"+str[i];
				Matcher matcher = Pattern.compile("%d\\{([a-zA-Z \\-]+)\\}").matcher(newMsg);
				if (matcher.find()) {
					String datePattern = matcher.group(1);
					DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(datePattern);
					converted = converted + newMsg.replaceAll("%d\\{([a-zA-Z \\-]+)\\}", dateFormat.format(ZonedDateTime.now()));
				}
			}
		}
		return converted;
	}
	
	// FIXME : kbank - 배치 파일명 생성 규칙에 따라 수정
	public String unzipAndSave(String aesKey, String jsonString, String rootFilePath, String fileNamePattern) throws Exception {
	    // gzippedValue 추출
	    String gzippedValue = getGzipValue(jsonString, "encData");
	    System.out.println("gzippedValue[" + gzippedValue + "]");

	    // 압축 해제
	    String unziped = GzipBase64Util.decompress(gzippedValue);
	    // AES 복호화
	    String text = CryptoUtil.decryptAES(aesKey, unziped);
	    
	    // 현재 처리 시각을 기반으로 파일명 생성
//	    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
//	    String fileName = LocalDateTime.now().format(formatter) + ".txt";

	    String fileName = updateDatePattern(fileNamePattern);
	    // TODO : Add additional pattern logic
	    
	    String filePath = Paths.get(rootFilePath, fileName).toString();
	    
	    Files.write(Paths.get(filePath), text.getBytes(), StandardOpenOption.CREATE);

	    // 결과 JSON 구성
	    ObjectNode replacedJson = mapper.createObjectNode();
	    replacedJson.put("filePath", filePath);
	    replacedJson.put("fileName", fileName);
	    return replacedJson.toString();
	}
}
