require("libs.utils")
local towerRange = 850

local hook_tower_kill = nil
local game_start_hook = nil
local effects = {}
local paint_hook = nil
local first_time = false


function SetTowerRangeDisplay(base_entity, range_value)
    local effect = dota.CreateEntityParticle(base_entity, "range_display")
    effect:SetControlPoint(1, dota.Vector(range_value,0,0) )
    table.insert(effects, effect)
end

function FetchTowers()
    effects = {}
    collectgarbage()
  
    local towers = dota.FindEntitiesWithName("CDOTA_BaseNPC_Tower")
    for _,tower in ipairs(towers) do
        SetTowerRangeDisplay(tower, towerRange)
    end
end

function OnPaint()
    if (first_time == false) then
        local loaded_player = dota.GameRules:GetInstance():GetLoadedPlayers()
        local expected_player = dota.GameRules:GetInstance():GetExpectedPlayers()
        --log.Warning(string.format("tower_range.lua loaded_player:%d, expected_player:%d\n",loaded_player,expected_player))
        if (loaded_player > 0 and expected_player > 0 and loaded_player == expected_player) then
            local towers = dota.FindEntitiesWithName("CDOTA_BaseNPC_Tower")
            --log.Warning(string.format("tower_range.lua towers:%d\n",table.getn(towers)))
            if (table.getn(towers) > 0) then
                first_time = true
                FetchTowers()
                log.Warning("tower_range.lua first_time\n")
            end
        end
    end
end

function OnLevelInit(map)
    first_time = false
end
function OnTowerKill()
    FetchTowers()
end

function Initialize()
    log.Warning("tower_range.lua start\n")
    paint_hook = dota.AddPaintHook(OnPaint)
    hook_tower_kill = dota.AddEventListener("dota_tower_kill", OnTowerKill)
    game_start_hook = dota.AddLevelInitHook(OnLevelInit)
    FetchTowers()
    log.Warning("tower_range.lua loaded\n")
end
