-- checking bot models for presence in the whitelist
local ss = analiz.libs.serv

-- -------------------------------------------------------------------------
-- -------------------------------------------------------------------------
-- -------------------------------------------------------------------------

function CreateBotWhiteListServ(option)
    local s = {models_ = {}}
    s.option = option
    -- --------------------------------------------
    function s:AddModel(model, ver)
        local m = self.models_[model]
        if m ~= nil then return end
        local i = {}
        i.name = model
        i.ver = ver
        self.models_[model] = i
    end
    -- --------------------------------------------
    function s:loadListId()
        ss.l("white.loadListId.Start")
        local sql = "select MODEL,ID from BotModelList where 1=0 "
        local count = 0
        for k, v in pairs(self.models_) do
            if v.id == nil then
                if (count % 3) == 0 then sql = sql .. "\n" end
                local name = v.name
                if name:find("'") ~= nil then
                    name = ss.ReplaceValue(name, "'", "''")
                end

                sql = sql .. " or (Model='" .. name .. "'  and Version='" ..
                          v.ver .. "') "
                count = count + 1
            end
        end
        ss.l("white.loadListId.count" .. count)
        if count == 0 then
            ss.l("white.loadListId.finish:true")
            return true
        end

        ss.e("CREATE_OR_CLEAR_STRING_MAP map_whiteBot")
        ss.s("tmp", sql)
        ss.l(sql)
        --   ss.a("1")
        ss.l("point 1")
        ss.e("ADD_MAP_FROM_SQL_V1 map_whiteBot PLIB MODEL ID $(tmp)")
        ss.l("point 2")
        local res = ss.map2obj("map_whiteBot")

        for k, v in pairs(res) do
            local m = self.models_[k]
            ss.l(k .. ":" .. v)
            m.id = v
        end

        ss.l("white.loadListId.finish:false")
        return false
    end

    function s:add_new_()
        ss.l("white.add_new_.start")
        sql = [[  BEGIN TRANSACTION
   
  DECLARE @maxID int
  DECLARE @curID int
  select  @maxID=max(ID) from BotModelList

  IF @maxID is NULL BEGIN
   set @maxID=30000000-1
  end
]]
        local count = 0
        local check_f =
            "      select @curID=max(ID) from [dbo].[BotModelList] where (Model='"
        local insert_f =
            "\n      INSERT INTO [dbo].[BotModelList]([ID],[Model],[Version],[Comment])     VALUES           ("
        for k, v in pairs(self.models_) do
            if v.id == nil then
                local name = v.name
                if name:find("'") ~= nil then
                    name = ss.ReplaceValue(name, "'", "''")
                end
                sql = sql .. check_f .. name .. "' and version='" .. v.ver ..
                          "')\n"
                sql = sql .. "IF @curID is NULL BEGIN\n"
                sql = sql .. "    set @maxID=@maxID+1\n"
                sql = sql .. insert_f .. "@maxID,'" .. name .. "','" .. v.ver ..
                          "',cast(GetDate() as varchar(100)) )\n"
                sql = sql .. "END\n"

                count = count + 1
            end
            if count > 20 then break end
        end

        sql = sql .. "\n  COMMIT TRANSACTION"
        ss.l("sql:" .. sql)
        ss.l(sql)
        --  ss.a("1")
        ss.s("tmp", sql)
        ss.e("EXEC_SQL PLIB $(tmp)")

    end

    -- --------------------------------------------
    function s:AddFinish()
        ss.l("white.Complete.Start")
        local ii = 0
        local NN = 20
        while true do
            if analiz:IsStop() then
                ss.l("white.Complete.user break")
                break
            end
            if self:loadListId() then break end
            if ii > 2 then
                ss.l("white.Complete:_______________________________:" .. ii)
                local sec = 5 + ii * 5
                ss.l("white.sleep " .. sec .. " sec...  ")
                ss.e("SLEEP sec " .. sec)
            end
            if ii > NN then
                ss.l("white.Complete:failed._______________________________:" ..
                         ii)
                ss.l("Sleep&&Restart")
                ss.e("SLEEP sec 15")
                if analiz:IsStop() then
                    ss.l("white.Complete.user break")
                    break
                end
                ss.e("_ABORT 11")
                break
            end
            self:add_new_()
            ii = ii + 1
        end
        ss.l("white.Complete.Finish")
    end
    -- --------------------------------------------
    function s:GetListID(model) 
      local m = self.models_[model]
      if m==nil then 
        ss.l("failed.GetListID for model:"..model)
        ss.l(debug.traceback())
      end
      return m.id end

    return s
end

-- -------------------------------------------------------------------------
-- -------------------------------------------------------------------------
-- -------------------------------------------------------------------------
botWhiteListServ = CreateBotWhiteListServ({})


