local S = minetest.get_translator("lzr_menu")

local build_ship = function(pos)
	minetest.place_schematic(pos, minetest.get_modpath("lzr_menu").."/schematics/lzr_menu_ship.mts", "0", {}, true, "")
	minetest.set_node(vector.add(lzr_globals.MENU_SHIP_POS, lzr_globals.MENU_SHIP_STARTBOOK_OFFSET), {name="lzr_menu:startbook", param2=0})
end

local emerge_callback = function(blockpos, action, calls_remaining, param)
	minetest.log("verbose", "[lzr_menu] emerge_callback() ...")
	if action == minetest.EMERGE_ERRORED then
		minetest.log("error", "[lzr_menu] Emerging error.")
	elseif action == minetest.EMERGE_CANCELLED then
		minetest.log("error", "[lzr_menu] Emerging cancelled.")
	elseif calls_remaining == 0 and (action == minetest.EMERGE_GENERATED or action == minetest.EMERGE_FROM_DISK or action == minetest.EMERGE_FROM_MEMORY) then
		build_ship(param.pos)
		minetest.log("action", "[lzr_menu] Ship emerged and built.")
	end
end

local SHIP_SIZE = { x = 30, y = 30, z = 30 }

local emerge_ship = function(pos)
	minetest.emerge_area(pos, vector.add(pos, SHIP_SIZE), emerge_callback, {pos=pos, size=SHIP_SIZE})
end

minetest.register_on_joinplayer(function(player)
	emerge_ship(lzr_globals.MENU_SHIP_POS)
	player:set_pos(vector.add(lzr_globals.MENU_SHIP_POS, lzr_globals.MENU_SHIP_PLAYER_SPAWN_OFFSET))
	player:set_look_horizontal(0)
	player:set_look_vertical(0)
	local inv = player:get_inventory()
	for i=1,inv:get_size("main") do
		inv:set_stack("main", i, "")
	end
end)

local on_punch = function(self, node, puncher)
	lzr_level_select.open_dialog(puncher)
end
local on_rightclick = function(self, node, clicker)
	lzr_level_select.open_dialog(clicker)
end

minetest.register_node("lzr_menu:startbook", {
	description = S("Start Game Book"),
	tiles = { "lzr_menu_book_top.png", "lzr_menu_book_bottom.png", "lzr_menu_book_side.png", "lzr_menu_book_side.png", "lzr_menu_book_end.png", "lzr_menu_book_end.png" },
	paramtype = "light",
	paramtype2 = "facedir",
	drawtype = "nodebox",
	node_box = {
		type = "fixed",
		fixed = {
			{ -0.4375, -0.5, -0.375, 0.4375, -0.4375, 0.1875 },
			{ -0.375, -0.4375, -0.375, 0.375, -0.375, 0.1875 }
		}
	},
	sunlight_propagates = true,
	on_construct = function(pos)
		local meta = minetest.get_meta(pos)
		meta:set_string("infotext", S("Start game"))
	end,
	on_punch = on_punch,
	on_rightclick = on_rightclick,
	groups = { snappy = 3, not_in_creative_inventory = 1, },
})

lzr_gamestate.register_on_enter_state(function(state)
	if state == lzr_gamestate.MENU then
		local player = minetest.get_player_by_name("singleplayer")
		lzr_player.set_play_inventory(player)
		lzr_gui.set_menu_gui(player)
		lzr_ambience.set_ambience("ocean")
	end
end)

