x_p = 15
y_p = 27
z_p = 15

currentPage = 1

function game_over()
	minetest.show_formspec("poop:game_over", "size[8,8]label[0,0;Game Over!]")
end

function you_win(player)
	-- teleport player to 0,0,0
	player:setpos({x=0, y=0, z=0})
	thanks = "Thanks for playing Shitting Simulator! We had a lot of fun making this game, and we hope you enjoyed it too! Thanks again!"
	storyFormspec =
    {
    "formspec_version[4]",
    "size[18, 16]",
    "bgcolor[brown]",
    "position[0.5, 0.5]",
    "style_type[button;bgcolor=yellow;textcolor=green]",
    "hypertext[1, 12.5; 12, 5;;<global halign=center color=black size=20 font=Regular>" .. thanks .. "]\n",
	"image[1, .2; 16, 12; thanks.png]",
    "button[13, 14.9; 4, 1;exit;Quit]"
    }
	minetest.show_formspec(player:get_player_name(), "poop:story", table.concat(storyFormspec, ""))
end

minetest.register_item(":", { -- Hand
type = "none",
wield_image = "Poop.png",
wield_scale = {x=1.5,y=2,z=4.5},
range = 5,
tool_capabilities = {
	max_drop_level = 0,
	full_punch_interval = 0.4,
	
	groupcaps = 
	{
		oddly_breakable_by_hand = {times={[1]=3.50,[2]=2.00,[3]=0.70}, uses=0},
		snappy = {times={[3]=0, [2]=0, [1]=0}, uses=0, maxlevel=3},
		crumbly = {times={[1]=0, [2]=0, [3]=0}, uses=0, maxlevel=3},
		cracky = {times={[1]=0, [2]=0, [3]=0}, uses=0, maxlevel=3},
		choppy = {times={[1]=0, [2]=0, [3]=0}, uses=0, maxlevel=3},
	},
	damage_groups = {fleshy = 3, snappy = 2},
}
})
minetest.register_on_player_receive_fields(function(player, formname, fields)
    if formname ~= "story:story_formspec" then
        return
    end

    if formname == "story:story_formspec" then    
        if fields.next then
            if currentPage >= 4 then
                minetest.close_formspec(player:get_player_name(), "story:story_formspec")
				-- teleport player to 10 9.5 18 
				player:setpos({x=15,y=21,z=15})
                return
            end
            currentPage = currentPage + 1 -- Fuck Lua and its lack of arithmetic assignment operators
            minetest.show_formspec(player:get_player_name(), "story:story_formspec", table.concat(getStoryFormspec(currentPage), "\n"))
            
        elseif fields.back and currentPage >= 0 then
            currentPage = currentPage - 1 -- Fuck Lua and its lack of arithmetic assignment operators
            minetest.show_formspec(player:get_player_name(), "story:story_formspec", table.concat(getStoryFormspec(currentPage), "\n"))
        
        elseif fields.exit then
            --minetest.kick_player(player:get_player_name(), "Fuck you in particular")
            minetest.request_shutdown("The game has crashed due to the citizen's neglience.\n This incident will be reported.")
        
        elseif fields.quit then
            minetest.after(0.2, function() minetest.show_formspec(player:get_player_name(), "story:story_formspec", table.concat(getStoryFormspec(currentPage), "\n")) end)
        end
    end
end)
storyText = {}
storyText[0] = "Click next to continue. Do NOT close the formspec by pressing the Escape key, or the game may break. To my knowledge, this is impossible to solve with the current Lua API."
storyText[1] = "Welcome to the state-of-the-art Shitting Simulator! A very advanced, educational, and culturally significant Minetest Game!"
storyText[2] = "So the story is simple: You've eaten so many pickles and beans and drank so much milk that your rectum will burst if you don't take a shit in the next two minutes."
storyText[3] = "You accidently use your flux capacitor and travel in time to the far future, where you find yourself in a city where you are shitting all over the place."
storyText[4] = "You have to run from the robocops and pack 100 pieces of shit into boxes! Good luck!"

function getStoryFormspec(number)
    storyFormspec =
    {
    "formspec_version[4]",
    "size[18, 16]",
    "bgcolor[brown]",
    "position[0.5, 0.5]",
    "style_type[button;bgcolor=yellow;textcolor=green]",
    "hypertext[1, 12.5; 12, 5;;<global halign=center color=black size=20 font=Regular>" .. storyText[number] .. "]\n",
    "image[1, .2; 16, 12;" .. number .. ".png]",
    "button[13, 12.3; 4, 1;back;Back]",
    "button[13, 13.6; 4, 1;next;Next]",
    "button[13, 14.9; 4, 1;exit;Quit]"
    }
    return storyFormspec
end

is_game_started = false
is_game_finished = false

minetest.register_on_newplayer(function(ObjectRef)
	minetest.place_schematic({x = 0, y = 0, z = 0}, minetest.get_modpath("poop") .. "/map.mts", "0", nil, true)
	ObjectRef:set_pos({x = 15, y = 21, z = 15})
end)


function ending()

end
function begining()

end

destruction_counter = {}
destruction_counter.nodesDestroyed = 0
local nodesDestroyedByHand = 0

local idText
local idMeter


minetest.register_item(":", { -- Hand
	type = "none",
	wield_image = "Poop.png",
	wield_scale = {x=1.5,y=2,z=4.5},
	range = 5,
	tool_capabilities = {
		max_drop_level = 0,
		full_punch_interval = 0.4,
		
		groupcaps = 
		{
			oddly_breakable_by_hand = {times={[1]=3.50,[2]=2.00,[3]=0.70}, uses=0},
			snappy = {times={[3]=0, [2]=0, [1]=0}, uses=0, maxlevel=3},
			crumbly = {times={[1]=0, [2]=0, [3]=0}, uses=0, maxlevel=3},
			cracky = {times={[1]=0, [2]=0, [3]=0}, uses=0, maxlevel=3},
			choppy = {times={[1]=0, [2]=0, [3]=0}, uses=0, maxlevel=3},
		},
		damage_groups = {fleshy = 3, snappy = 2},
	}
})



minetest.register_on_joinplayer(function(player)
    meta = player:get_meta()
    

    idText = player:hud_add({
        hud_elem_type = "text",
        position      = {x = .5, y = .5},
        offset        = {x = 0,   y = 0},
        text          = nodesDestroyed,
        alignment     = {x = 0, y = 0},  -- center aligned
        scale         = {x = 100, y = 100}, -- covered later
    })
    
    player:hud_add({
        hud_elem_type = "image",
        position  = {x = 1, y = .5},
        offset    = {x = -515, y = 23},
        text      = "destruction_counter_meter_empty.png",
        scale     = {x = 4, y = 4},
        alignment = {x = 1, y = 0},
    })

    idMeter = player:hud_add({
        hud_elem_type = "image",
        position  = {x = 1, y = .5},
        offset    = {x = -510, y = 23},
        text      = "destruction_counter_meter_full.png",
        scale     = {x = 0, y = 4},
        alignment = {x = 1, y = 0},
    })
end)

function destruction_counter.updateCounter(player)
    if not player then
        return
    end
    
    local totalDestruction = destruction_counter.nodesDestroyed + math.floor(nodesDestroyedByHand / 10)
    local percentage = (totalDestruction / 100 * 4)
    if percentage > 100 then
        percentage = 100
    end
    player:hud_change(idText, "text", "Shitting & Packing Meter: " .. totalDestruction)
    player:hud_change(idMeter, "scale", {x = percentage, y = 4})
end

function sraj_dzwiek()
	--make random sound
	local sounds = {
		"shitting1",
		"shitting2",
		"shitting3"}
	local sound = sounds[math.random(1, #sounds)]
	minetest.sound_play(sound, {pos = pos, gain = 2.0, max_hear_distance = 10})

end
function pakuj_guwno()
	local sounds = {
		"shit_packing1",
		"shit_packing2",
		"shit_packing3"}
	local sound = sounds[math.random(1, #sounds)]
	minetest.sound_play(sound, {pos = pos, gain = 2.0, max_hear_distance = 10})
end
minetest.register_node("poop:box", {
	description = "cardboard box",
	tiles = {"box_top_closed.png","box_top_closed.png", "box_long_side.png", "box_long_side.png", "box_long_side.png", "box_long_side.png"},
	
	drop = 'poop:box',
	legacy_mineral = true,
	drawtype = "nodebox",
	paramtype = "light",
	node_box = {
		type = "fixed",
		fixed = {
			{-0.3125, -0.5, -0.375, 0.3125, -0.0625, 0.375}, -- NodeBox1
		}
	}
})

minetest.register_node("poop:ladder_steel", {
	description = "Ladder",
	drawtype = "signlike",
	tiles = {"ladder.png"},
	paramtype = "light",
	paramtype2 = "wallmounted",
	sunlight_propagates = true,
	walkable = false,
	climbable = true,
	is_ground_content = false,
	selection_box = {
		type = "wallmounted",
		--wall_top = = <default>
		--wall_bottom = = <default>
		--wall_side = = <default>
	},
	groups = {cracky = 2},
})


-- make a tool called flashlight that can be used to light up the world
minetest.register_tool("poop:flashlight", {
	description = "Flashlight",
	inventory_image = "flashlight.png",
	wield_image = "flashlight.png",
	wield_scale = {x=1,y=1,z=1},
	tool_capabilities = {
		full_punch_interval = 1.0,
		max_drop_level=0,
		groupcaps={
			cracky = {times={[1]=3.00, [2]=0.70, [3]=0.40}, uses=20, maxlevel=1},
		},
		damage_groups = {fleshy=2},
	},
	light_source = 14,
})

minetest.register_tool("poop:tool", {
    description = "My Tool",
    inventory_image = "flux_capacitor.png",
    tool_capabilities = {
        full_punch_interval = 1.5,
        max_drop_level = 1,
        groupcaps = {
            crumbly = {
                maxlevel = 2,
                uses = 20,
                times = { [1]=1.60, [2]=1.20, [3]=0.80 }
            },
        },
        damage_groups = {fleshy=2},
    },
})
minetest.register_node("poop:floor", {
	description = "Floor",
	tiles = {"floor.png"},
	
	drop = 'poop:floor',
	legacy_mineral = true, groups = {cracky=3, stone=1},
})

minetest.register_node("poop:Poop", {
	description = "Just Shit",
	tiles = {"Poop.png"},
	drop = 'poop:PoopItem', groups = {cracky=3, stone=1},
})

minetest.register_node("poop:tv", {
	description = "CRT TV",
	tiles = {
		"PC2.png", 
		"PC2.png",
		"PC2.png",
		"PC2.png",
		"PC2.png",
		"PC.png"
	},
	paramtype2 = "facedir",
	drop = 'poop:Poop', groups = {cracky=3, stone=1},
})

minetest.register_node("poop:bricks", {
	description = "Bricks",
	tiles = {"Bricks.png"},
	
	drop = 'poop:grey_bricks', groups = {cracky=3, stone=1},
})
minetest.register_node("poop:grey_bricks", {
	description = "Bricks 2",
	tiles = {"Bricks2.png"}, groups = {cracky=3, stone=1},
	
	drop = 'poop:grey_bricks', groups = {cracky=3, stone=1},
})
minetest.register_node("poop:planks", {
	description = "Planks",
	tiles = {"Planks.png"},
	
	drop = 'poop:planks', groups = {cracky=3, stone=1},
})
minetest.register_node("poop:purpleblock", {
	description = "Purple Block",
	tiles = {"purpleblock.png"},
	
	drop = 'poop:purpleblock', groups = {cracky=3, stone=1},
})
minetest.register_node("poop:purpleblock", {
	description = "Purple Block",
	tiles = {"purpleblock.png"},
	
	drop = 'poop:purpleblock', groups = {cracky=3, stone=1},
})
minetest.register_node("poop:redblock", {
	description = "Red Block",
	tiles = {"redblock.png"},
	
	drop = 'poop:redblock', groups = {cracky=3, stone=1},
})

minetest.register_node("poop:aquablock", {
	description = "Aqua Block",
	tiles = {"aquablock.png"},
	
	drop = 'poop:aquablock', groups = {cracky=3, stone=1},
})
minetest.register_node("poop:glass", {
	description = "Glass",
	tiles = {"glass.png"},
	
	drop = 'poop:glass', groups = {cracky=3, stone=1},
})
minetest.register_node("poop:Poop2", {
	description = "Poop with more density", 
	tiles = {"sraka.png"},
	
	drop = 'poop:Poop', groups = {cracky=3, stone=1},
})

minetest.register_node("poop:glowing_block", {
	description = "Glowing Block",
	tiles = {"glowing_block.png"},
	
	drop = 'poop:glowing_block', groups = {cracky=3, stone=1},
	light_source = 14
})

minetest.register_node("poop:flux_capacitor", {
	description = "Flux Capacitor from Back to the Future",
	tiles = {"fluxcap2.png", "fluxcap2.png","fluxcap2.png","fluxcap.png","fluxcap2.png","fluxcap2.png"},
	
	drop = 'poop:Poop', groups = {cracky=3, stone=1},
})
minetest.register_alias("mapgen_stone", "poop:floor")

local pooped_things = 0

minetest.register_craftitem("poop:plumba", {
	description = "Plumba",
	inventory_image = "plumba.png",
	on_use = function(itemstack, user, pointed_thing)
		-- check if pointing at a node
		if pointed_thing.type ~= "node" then
			return
		end
		if pooped_things >= 200 then
			is_game_finished = true
			you_win(user)
			return
		end
		-- get node at pointed thing position
		local node = minetest.get_node(pointed_thing.under)
		-- check if node is poop
		if node.name == "poop:Poop" then
			minetest.remove_node(pointed_thing.under)
			minetest.add_node(pointed_thing.under, {name="poop:box"})			
			minetest.chat_send_player(user:get_player_name(), "You packed "..pooped_things.." shits!")
			pooped_things = pooped_things + 1
			
			if pooped_things == 100 then
				-- stop first music loop
				minetest.sound_stop(first_music)
				-- play second music loop
				minetest.sound_play("shit_all_over_the_place", {
					gain = 1, 
					pitch = 1,
					loop = true,
				})

			end

			destruction_counter.nodesDestroyed = pooped_things
			destruction_counter.updateCounter(user)
			pakuj_guwno()
			return itemstack
		else if node.name == "poop:Poop2" then
			minetest.remove_node(pointed_thing.under)
			minetest.add_node(pointed_thing.under, {name="poop:box"})
			minetest.chat_send_player(user:get_player_name(), "You packed "..pooped_things.." shits!")
			pakuj_guwno()
			pooped_things = pooped_things + 1
			destruction_counter.nodesDestroyed = pooped_things
			destruction_counter.updateCounter(user)
			return itemstack
		end

		end
		end
	})


minetest.register_craftitem("poop:pooper", {
	description = "Pooper",
	inventory_image = "SHITitem.png",
	on_use = function(itemstack, user, pointed_thing)
		-- check if pointing at a node
		if pointed_thing.type ~= "node" then
			return
		end
		-- make a random number between 1 and 10
		local random_number = math.random(1, 10)
		if random_number < 5 then
			local node = minetest.get_node(pointed_thing.above)
			if node.name == "air" then
				minetest.add_node(pointed_thing.above, {name="poop:Poop"})
			else
				minetest.add_node(pointed_thing.under, {name="poop:Poop"})
			end
		else 
			local node = minetest.get_node(pointed_thing.above)
			if node.name == "air" then
				minetest.add_node(pointed_thing.above, {name="poop:Poop2"})
			else
				minetest.add_node(pointed_thing.under, {name="poop:Poop2"})
			end
		end
		sraj_dzwiek()
		return itemstack
	end,
})

minetest.register_on_joinplayer(function(player) 
	-- teleport to 0,0,0
	player:setpos({x=0, y=0, z=0})
	minetest.show_formspec(player:get_player_name(), "story:story_formspec", table.concat(getStoryFormspec(1), "\n"))
	player:get_inventory():set_list("main", {})
	-- set time to day
	minetest.set_timeofday(0.5)
	first_music = minetest.sound_play("pooping_together", {
		gain = 1, 
		pitch = 1,
		loop = true,
	})
	player:get_inventory():add_item("main", "poop:plumba")
	player:get_inventory():add_item("main", "poop:pooper")


	minetest.setting_set("time_speed", 0)
	minetest.set_timeofday(0)

	begining()
end)