-- 统一的服务基础逻辑
local _service_name, _service_path = ...
assert(_service_name, "_service_name nil")
assert(_service_path, "_service_path nil")

SERVICE_NAME = _service_name
local _arguments = table.pack(...)

local skynet = require "skynet"
require "skynet.manager"

require "sharetable"
require "cluster"
require "multicast"
require "datacenter"

local function _exception(e)
    skynet.error(e)
    return e
end

local _xpcall = function(f, ...)
    return xpcall(f, _exception, ...)
end

local single -- 服务逻辑单例对象

local _info = function()
end

local _dispatch = function(session, source, cmd, ...)
    local func = single:get_cmd_func(cmd)
    if not func then
        skynet.retpack({
            ok = false,
            msg = string.format("[%s]UNKNOWN_CMD[%s]FROM[%s]", _service_name, cmd, tostring(source)),
        })
        return
    end

    if session > 0 then
        skynet.retpack(_xpcall(func, single, ...))
    else
        _xpcall(func, single, ...)
    end
end

skynet.start(function()
    single = require(_service_path):instance(table.unpack(_arguments, 2, _arguments.n))
    assert(single.dispatch, "zeus service dispatch function nil")

    skynet.dispatch("lua", _dispatch)
    skynet.info_func(_info)

    local fsm = single:get_fsm()
    fsm.initial()
    fsm.running()

    single:add_timer(_info, 3600)
end)
