package com.yfd.platform.component.sntp;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//@Component
@RequiredArgsConstructor
@Slf4j
public class SNTPServer implements ApplicationRunner {

    @Override
    @Async
    public void run(ApplicationArguments applicationArguments) {
        int port = 123; // SNTP server port

        try (DatagramSocket serverSocket = new DatagramSocket(port)) {
            log.info("SNTP Server is running on port " + port);

            while (true) {
                byte[] receiveData = new byte[48];
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);

                long currentTimeMillis = System.currentTimeMillis();
                // 获取当前时间信息
                long currentTime = System.currentTimeMillis();
                long ntpTime = currentTime + 2208988800000L; // Unix时间戳起始时间为1900年，Java起始时间为1970年
                ntpTime -= 2000000000;
                // 构造NTP响应数据包
                byte[] buffer = new byte[48];
                buffer[0] = (byte) 0x1B; // 设置版本号和模式
                for (int i = 1; i < 48; i++) {
                    buffer[i] = (byte) 0; // 设置其他字段为0
                }
                long seconds = ntpTime / 1000;
                long fraction = (long) ((ntpTime % 1000) * (1L << 32) / 1000);
                buffer[40] = (byte) ((seconds >> 24) & 0xFF);
                buffer[41] = (byte) ((seconds >> 16) & 0xFF);
                buffer[42] = (byte) ((seconds >> 8) & 0xFF);
                buffer[43] = (byte) (seconds & 0xFF);
                buffer[44] = (byte) ((fraction >> 24) & 0xFF);
                buffer[45] = (byte) ((fraction >> 16) & 0xFF);
                buffer[46] = (byte) ((fraction >> 8) & 0xFF);
                buffer[47] = (byte) (fraction & 0xFF);

                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();
                DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, clientAddress, clientPort);
                serverSocket.send(sendPacket);
                log.info("Sent current time to client: " + new Date(currentTimeMillis));
            }
        } catch (Exception e) {
            log.error(e.getMessage());;
        }
    }

}

