package com.persagy.calendar.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;
import org.apache.commons.net.ntp.TimeStamp;

import com.persagy.common.utils.DateUtil;

/**
 * @version
 * @description
 * @company persagy
 * @author zhangqiankun
 * @since 2020年9月7日: 下午3:32:07
 */
public class NTPClientUtil {

	private static NTPUDPClient ntpudpClient = null;
	private static InetAddress inetAddress = null;
	private static List<String> hostList = new ArrayList<String>();
	
	static {
		hostList.add("ntp1.aliyun.com");
		hostList.add("ntp2.aliyun.com");
		hostList.add("ntp3.aliyun.com");
		hostList.add("ntp4.aliyun.com");
		hostList.add("ntp5.aliyun.com");
		hostList.add("ntp6.aliyun.com");
		hostList.add("ntp7.aliyun.com");
	}
	
	public static void main(String[] args) {
		NTPClientUtil.initNTPClient("ntp1.aliyun.com", 5000);
		String ntpServerTime = getNTPServerTime();
		System.out.println(ntpServerTime);
		stopNTPClient();
	}
	
	public static synchronized String getNTPServerTime() {
		for (String host : hostList) {
			try {
				initNTPClient(host, 5000);
				
				TimeInfo timeInfo = ntpudpClient.getTime(inetAddress);
				TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();
				Date date = timeStamp.getDate();
				return DateUtil.format(date, DateUtil.FORMAT_DATE_YYYYMMDDHHMMSS);
			} catch (Exception e) {
				stopNTPClient();
			}
		}
		return null;
	}
	
	private static synchronized void initNTPClient(String host, int timeout) {
		ntpudpClient = new NTPUDPClient();
		// 设置连接超时时间
		ntpudpClient.setDefaultTimeout(timeout);
		try {
			inetAddress = InetAddress.getByName(host);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}

	private static synchronized void stopNTPClient() {
        if (null != ntpudpClient) {
        	ntpudpClient.close();
        }
    }

}