local util = require("util")

local function created_items()
  return
  {
    ["iron-plate"] = 8,
    ["wood"] = 1,
    ["pistol"] = 1,
    ["firearm-magazine"] = 10,
    ["burner-mining-drill"] = 1,
    ["stone-furnace"] = 1
  }
end

local function chart_starting_area()
  local r = storage.chart_distance or 200
  local force = game.forces.player
  local surface = game.surfaces[1]
  local origin = force.get_spawn_position(surface)
  force.chart(surface, {{origin.x - r, origin.y - r}, {origin.x + r, origin.y + r}})
end

local function init()
  if storage.init_ran then
    return
  end

  storage.init_ran = true

  chart_starting_area()
end

local function on_player_created(e)
  local player = game.get_player(e.player_index)
  local character = player.character
  player.character = nil
  if character then
    character.destroy()
  end

  util.insert_safe(player, storage.created_items)

  init()
end

local sandbox = {}

function sandbox.on_init()
  storage.created_items = storage.created_items or created_items()
end

function sandbox.on_configuration_changed()
  storage.created_items = storage.created_items or created_items()
end

sandbox.events = {
  [defines.events.on_player_created] = on_player_created,
}

local remote_interface = {}

function remote_interface.set_chart_distance(value)
  storage.chart_distance = tonumber(value) or error("Remote call parameter to sandbox set chart distance must be a number")
end

function remote_interface.get_created_items()
  return storage.created_items
end
function remote_interface.set_created_items(new_items)
  storage.created_items = new_items or error("Remote call parameter to freeplay set created items can't be nil.")
end

if not remote.interfaces["sandbox"] then
  remote.add_interface("sandbox", remote_interface)
end

return sandbox
