package com.eactive.eai.custom.message;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

import org.apache.commons.lang3.StringUtils;

import com.eactive.eai.common.server.Keys;
import com.eactive.eai.common.util.StringUtil;
import com.eactive.eai.common.util.UUID;

/**
 * 1. 기능 : UUID Generation Class 2. 처리 개요 : * - 3. 주의사항
 *
 * @author :
 * @version : v 1.0.0
 * @see : 관련 기능을 참조
 * @since : :
 */
public final class GUIDGeneratorKAKAOCARD {

	private static final DateTimeFormatter SDF_YYYYMMDDHHMMSSMS = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

	/*
	 * 날짜(17) + "-"(1) + 시스템코드(3) + hostname(6) + 일련번호(5) + "-"(1) + 001(3)
	 * 
	 */

	public static final int GUID_LENGTH = 33; // seq값 제외부분

	/**
	 * 1. 기능 : Private 생성자 2. 처리 개요 : - 3. 주의사항 - Instance 생성하지 못함
	 **/
	private GUIDGeneratorKAKAOCARD() {
	}

	public synchronized static String getGUID(String systemCode) {
		StringBuilder sb = new StringBuilder();
		sb.append(SDF_YYYYMMDDHHMMSSMS.format(ZonedDateTime.now()));
		sb.append("-");
		sb.append(systemCode);
		sb.append(UNIQUE_NUM);
		char[] formatSeq = { '0', '0', '0', '0', '0' };
		char[] seqCharArray = String.valueOf(seq).toCharArray();
		int destPos = formatSeq.length - seqCharArray.length;
		System.arraycopy(seqCharArray, 0, formatSeq, destPos, seqCharArray.length);

		sb.append(formatSeq);
		seq++;
		if (seq > 99999) {
			seq = 1;
		}

		return sb.toString() + "-" + "001";
	}

	private static String UNIQUE_NUM;
	private static int seq = 1;
	private static int hostlength = 6;
	static {
		String uniqueValue = System.getProperty(Keys.SERVER_KEY);
		if (StringUtils.isBlank(uniqueValue)) {
			try {
				uniqueValue = java.net.InetAddress.getLocalHost().getHostName();
			} catch (Exception e) {
				uniqueValue = StringUtil.stringFormat("", false, 'X', hostlength);
			}
		}
		if (uniqueValue.length() > hostlength) {
			uniqueValue = uniqueValue.substring(uniqueValue.length() - hostlength, uniqueValue.length());
		} else if (uniqueValue.length() < hostlength) {
			uniqueValue = StringUtil.stringFormat(uniqueValue, false, 'X', hostlength);
		}
		UNIQUE_NUM = uniqueValue.toUpperCase();
	}

	public static void main(String[] args) {
		String guid = getGUID("FEP");
		System.out.println("[" + guid.length() + "]" + guid);
	}
}