package com.jay.monitor.data.server.factory.generate;

import com.jay.monitor.data.server.enums.DataSplitType;
import com.jay.monitor.data.server.factory.ChangeConsumer;
import com.jay.monitor.data.server.factory.IdGenerateService;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Module 编号生成器
 * @Description 根据小时生成
 * @Author liukaixiong
 * @Date 2020/11/5 19:13
 */
@Component
public class HourIdGenerate implements IdGenerateService {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHH");

    private volatile long hourTimestamp = getHourTimestamp();

    private volatile String defaultId = resetCounter(hourTimestamp);

    protected long getHourTimestamp() {
        return TimeUnit.MILLISECONDS.toHours(System.currentTimeMillis());
    }

    private String resetCounter(long timestamp) {
        String id = sdf.format(new Date());
        this.hourTimestamp = getHourTimestamp();
        this.defaultId = id;
        return id;
    }

    @Override
    public DataSplitType splitType() {
        return DataSplitType.HOUR;
    }

    @Override
    public String getCurrentId(ChangeConsumer<String> consumer) {
        long timestamp = getHourTimestamp();
        String id = defaultId;
        if (timestamp != hourTimestamp) {
            synchronized (this) {
                if (timestamp != hourTimestamp) {
                    id = resetCounter(timestamp);
                    consumer.accept(id);
                }
            }
        }
        return id;
    }

    @Override
    public String getNextId(String id) {
        return null;
    }
}
