analiz:log("--serv2.lua-")

local ss = analiz.libs.serv
local tick = CreateTimeServ()

function restart_service(msg)
    ss.l("restart_service:" .. msg)
    if true then
        ss.l("restart_service.skip restart")
        return
    end
    ss.e("restart_service.l:" .. msg)
    ss.e("echo !!!!restart!!!")
    ss.e("calc_param pskill_exe $(_ANALIZ_BIN)\\pskill.exe")
    ss.e("GET_SHORT_PATH pskill_exe $(pskill_exe)")
    ss.e("GET_CURRENT_PROCESS_ID txm_pid")
    ss.e("echo execute $(pskill_exe) $(txm_pid)")
    ss.e("execute $(pskill_exe) $(txm_pid)")
    ss.e("_abort 1")
end

-- ------------------------------------------------------------------------------
function GetRootTempDir()
    ss.e("GETENV_PARAM prospero_temp PROSPERO_TEMP")
    local tmp = ss.g("prospero_temp")
    if tmp ~= "" then return tmp end
    -- default temp
    return ss.b("$(temp)")
end
-- ------------------------------------------------------------------------------
function GetProsperoHostName()
    ss.e("GETENV_PARAM tmp PROSPERO_HOST")
    local tmp = ss.g("tmp")
    if tmp ~= "" then return tmp end
    -- default temp
    return ss.b("$(COMPUTERNAME)")

end

-- ------------------------------------------------------------------------------
function GetCurrentListID_(params)
    ss.l("GetCurrentListID")
    local function get_(params)
        --    l("get.1")
        ss.s("tmp", "")
        ss.s("tmp_r", "")
        ss.s("tmp_m", "")
        ss.s("tmp_s",
             "select cast(max(ID) as varchar(20)) as C from CurrentListTable")
        local tt = tick.now()
        ss.e("ANALIZ_SAFE_EXECUTE tmp_r tmp_e  SET_PARAM_FROM_SQL tmp " ..
                 params.pwd_plib .. "  C $(tmp_s)")
        local delta = tick.to_msec(tick.now() - tt)
        if delta > 200 then
            ss.l("GetCurrentListID.slow:" .. delta .. " msec")
        end

        local ret = {id = analiz:get("tmp"), emessage = analiz:get("tmp_m")}
        return ret
    end

    local i = 0
    while true do
        local r = get_(params)
        if r.emessage == "" then return r.id end
        ss.l("count:" .. i .. ",emessage:" .. r.emessage)
        i = i + 1
        if i > 10 then
            restart_service("failed:" .. r.emessage)
            return -1
        end
        ss.e("SLEEP sec 1")

    end
    return -1
end
local lastlistid_=-1
function GetCurrentListID(params)
  local id = GetCurrentListID_(params)
  if id==-1 then 
     id=lastlistid_ 
     return id
  end
  lastlistid_=id
  return id
end

