local skynet = require "skynet"
local conf = require("tracing.conf")
local floor = math.floor
local format = string.format
----------------------------------------------

local M = {}

local trace_id = 1
local last_unixtime = 0
-- 节点id(8位 255) + 服务地址(12位 4095) + 时间(32位) + 自增id(12位)
local PRE_TRACE_ID = (conf.node_id << 56) + (skynet.self() << 44)
function M.get_timestamp()
    return floor(skynet.hpc() / 1000) -- 微妙
end

function M.generate_span_id(tm)
    tm = tm // 1000
    if last_unixtime ~= tm then
        trace_id = 1
    end
    local id = (tm << 12) + trace_id
    local spanid = format("%016x", PRE_TRACE_ID + id)

    if last_unixtime == tm then
        trace_id = trace_id + 1
    end
    last_unixtime = tm
    return spanid
end

return M
