local skynet = require "skynet"
require "tracing.init"

local CMD = {}

local CLIENT_FD
local GATE
-- local WATCHDOG

skynet.register_protocol {
    name = "client",
    id = skynet.PTYPE_CLIENT,
    unpack = skynet.tostring,
    dispatch = function(fd, _, msg)
        assert(fd == CLIENT_FD) -- You can use fd to reply message
        skynet.ignoreret() -- session is fd, don't call skynet.ret
        skynet.tracing_send(GATE, {
            cmd = "response",
        }, CLIENT_FD, msg)
    end,
}

function CMD.start(tracer, conf)
    local fd = conf.client
    GATE = conf.gate
    -- WATCHDOG = conf.watchdog
    CLIENT_FD = fd

    skynet.tracing_call(GATE, "forward", tracer, fd)
end

-- tracer
function CMD.disconnect(_)
    -- todo: do something before exit
    skynet.exit()
end

skynet.start(function()
    skynet.dispatch("lua", function(_, _, cmd, tracer, ...)
        skynet.trace(tracer)
        local f = CMD[cmd]
        skynet.ret(skynet.pack(f(tracer, ...)))
    end)
end)
