local Public = require 'maps.mountain_fortress_v3.stateful.table'

local bp =
'[encoded data, 4309 characters]'

function Public.blueprint()
    local position = { x = -500, y = 503 }
    local active_surface_index = Public.get('active_surface_index')
    local surface = game.get_surface(active_surface_index)
    if not surface or not surface.valid then
        return
    end

    surface.daytime = 0.5
    surface.freeze_daytime = true
    surface.min_brightness = 0.3
    surface.brightness_visual_weights = { 1, 1, 1 }
    surface.request_to_generate_chunks(position, 1)
    surface.request_to_generate_chunks({ 0, 0 }, 1)
    surface.force_generate_chunk_requests()

    local ents = surface.find_entities_filtered({ area = { { position.x - 70, position.y - 70 }, { position.x + 70, position.y + 70 } } })
    if #ents == 0 then
        return
    end

    for _, e in pairs(ents) do
        if e and e.valid then
            e.destroy()
        end
    end

    local item = surface.create_entity { name = 'item-on-ground', position = position, stack = { name = 'blueprint', count = 1 } }
    if not item then
        return
    end

    local success = item.stack.import_stack(bp)
    if success <= 0 then
        local ghosts = item.stack.build_blueprint { surface = surface, force = 'player', position = position, build_mode = defines.build_mode.forced }
        for _, ghost in pairs(ghosts) do
            local _, ent = ghost.silent_revive({ raise_revive = true })
            if ent and ent.valid then
                ent.destructible = false
                ent.minable_flag = false
            end
        end
    end

    if item.valid then
        item.destroy()
    end
end

function Public.nuke_blueprint()
    local position = { x = -500, y = 503 }
    local active_surface_index = Public.get('active_surface_index')
    local surface = game.get_surface(active_surface_index)
    if not surface or not surface.valid then
        return
    end

    local radius = 512
    local area = { { position.x - radius, position.y - radius }, { position.x + radius, position.y + radius } }
    for _, entity in pairs(surface.find_entities_filtered { area = area, name = 'programmable-speaker' }) do
        if entity and entity.valid then
            entity.destroy()
        end
    end
end

return Public
