local FlashTable = {}
local SquareTable = {}
local function CheckLight()
    for k, v in pairs(FlashTable) do
        if v.Light and not SquareTable[k] then
            getCell():removeLamppost(v.Light)
            FlashTable[k] = nil
        end
    end
    for k, v in pairs(SquareTable) do
        if not FlashTable[k] then
            FlashTable[k] = {
                SquareName = k,
                Light = nil
            }
            local newlight = IsoLightSource.new(v:getX(), v:getY(), 0, 0.8, 0.6, 0.8, 6)
            FlashTable[k].Light = newlight
            getCell():addLamppost(newlight)
        end
    end
end

Events.OnTick.Add(CheckLight)

local function CheckLightSet(player)
    if not player then
        return
    end
    local vehicle = player:getVehicle()
    if not vehicle then
        return
    end
    local HeliType = GetHeliType(vehicle)
    if not HeliType then
        return
    end
    SquareTable = {}
    if vehicle:getHeadlightsOn() then
        local CurrentSquare = vehicle:getSquare()
        local dirc = player:getForwardDirection():getDirection()
        local deltX = math.cos(dirc)
        local deltY = math.sin(dirc)
        local currentX = CurrentSquare:getX()
        local currentY = CurrentSquare:getY()
        local currentZ = CurrentSquare:getZ()
        local offsetX = 0
        local offsetY = 0
        local distanceTravelled = 0
        local maxDistance = 20
        local minDistance = 3
        while distanceTravelled < maxDistance do
            offsetX = offsetX + deltX * 1
            offsetY = offsetY + deltY * 1
            distanceTravelled = distanceTravelled + 1
            if distanceTravelled >= minDistance then
                local newSquare = getCell():getGridSquare(currentX + offsetX, currentY + offsetY, currentZ)
                if newSquare then
                    local StringName = currentX + offsetX .. "_" .. currentY + offsetY
                    SquareTable[StringName] = newSquare
                end
                if distanceTravelled >= maxDistance then

                    break
                end
            end
        end

    end
end

Events.OnPlayerUpdate.Add(CheckLightSet)
