package com.eactive.eai.custom.message;

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

import com.eactive.eai.common.util.DatetimeUtil;
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 GUIDGeneratorKJB {

	/*
	 * 그룹사코드(3) + 호스트명(8) + 서버구분번호(2) + 일자(8) + 전문생성시간(6) + 일련번호(6) + 시스템경로번호(3, '001')
	 */

	public static final int GUID_LENGTH = 33; // 시스템경로번호 제외부분

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

	public synchronized static String getGUID(String groupCmpCd) {
		String guid = groupCmpCd + UNIQUE_NUM;
		guid = guid + DatetimeUtil.getCurrentDateTime();

		if(seq < 10) {
			guid = guid + "00000" + seq;
		}
		else if(seq < 100) {
			guid = guid + "0000" + seq;
		}
		else if(seq < 1000) {
			guid = guid + "000" + seq;
		}
		else if(seq < 10000) {
			guid = guid + "00" + seq;
		}
		else if(seq < 100000) {
			guid = guid + "0" + seq;
		}
		else {
			guid = guid + seq;
		}

		seq ++;
		if(seq > 999999) {
			seq = 1;
		}

		return guid + "001";
	}

    private static String UNIQUE_NUM;
    private static int seq = 1;
    static {
    	String hostname = "";
    	try {
    		hostname = java.net.InetAddress.getLocalHost().getHostName();
    	}
    	catch(Exception e) {
    		hostname = "________";
    	}
    	
    	if(hostname.getBytes().length != 8) {
    		if(hostname.getBytes().length < 8) {
        		hostname = StringUtils.leftPad(hostname, 8, '_');
    		} else if(hostname.getBytes().length > 8) {
        		hostname = StringUtils.substring(hostname, 0, 8);
    		}
    	}
    	
    	String serverName = System.getProperty(Keys.SERVER_KEY);
    	String instid = "00";
    	if(serverName != null && serverName.length() > 2) {
    		instid = serverName.substring(serverName.length()-2, serverName.length());
    	}

    	UNIQUE_NUM = hostname.toUpperCase() + instid;
    }

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