package com.njcn.gather.tools.comtrade.comparewave.core.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 时间结构体
 * 对应C代码：clock_struct
 * @author hongawen
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ClockStruct {
    
    private int year;
    private int month;
    private int day;
    private int hour;
    private int minute;
    private int second;
    private int microSecond;
    
    /**
     * 格式化时间字符串
     */
    public String format() {
        return String.format("%04d-%02d-%02dT%02d:%02d:%02d.%03d",
            year, month, day, hour, minute, second, microSecond/1000);
    }
    
    /**
     * 从时间戳创建时间结构体
     * <p>时间戳单位为微秒</p>
     * 
     * @param timestamp 微秒级时间戳
     * @return 时间结构体实例
     */
    public static ClockStruct fromTimestamp(long timestamp) {
        // 微秒转换为秒和微秒部分
        long totalSeconds = timestamp / 1_000_000;
        int microSeconds = (int) (timestamp % 1_000_000);
        
        // 使用Java的时间API进行转换
        java.time.Instant instant = java.time.Instant.ofEpochSecond(totalSeconds);
        java.time.LocalDateTime dateTime = java.time.LocalDateTime.ofInstant(instant, java.time.ZoneId.systemDefault());
        
        return new ClockStruct(
            dateTime.getYear(),
            dateTime.getMonthValue(),
            dateTime.getDayOfMonth(),
            dateTime.getHour(),
            dateTime.getMinute(),
            dateTime.getSecond(),
            microSeconds
        );
    }
    
    /**
     * 从毫秒时间戳创建时间结构体
     * 
     * @param timestampMillis 毫秒级时间戳
     * @return 时间结构体实例
     */
    public static ClockStruct fromTimestampMillis(long timestampMillis) {
        return fromTimestamp(timestampMillis * 1000);
    }
    
    /**
     * 获取当前时间的时间结构体
     * 
     * @return 当前时间的时间结构体
     */
    public static ClockStruct now() {
        java.time.LocalDateTime now = java.time.LocalDateTime.now();
        long nanoTime = System.nanoTime();
        int microSeconds = (int) ((nanoTime / 1000) % 1_000_000);
        
        return new ClockStruct(
            now.getYear(),
            now.getMonthValue(),
            now.getDayOfMonth(),
            now.getHour(),
            now.getMinute(),
            now.getSecond(),
            microSeconds
        );
    }
}