--Blockmanager is required for setting basic Block properties
local blockManager = require("blockManager")

--Create the library table
local rope = {}
--BLOCK_ID is dynamic based on the name of the library file
local blockID = BLOCK_ID

--Defines Block config for our Block. You can remove superfluous definitions.
local ropeSettings = {
	id = blockID,
	--Frameloop-related
	frames = 1,
	framespeed = 8, --# frames between frame change

	--Identity-related flags:
	semisolid = true, --top-only collision
	sizable = true, --sizable block
	--passthrough = false, --no collision
	--bumpable = false, --can be hit from below
	--lava = false, --instakill
	--pswitchable = false, --turn into coins when pswitch is hit
	--smashable = 0, --interaction with smashing NPCs. 1 = destroyed but stops smasher, 2 = hit, not destroyed, 3 = destroyed like butter

	--floorslope = 0, -1 = left, 1 = right
	--ceilingslope = 0,

	--Emits light if the Darkness feature is active:
	--lightradius = 100,
	--lightbrightness = 1,
	--lightoffsetx = 0,
	--lightoffsety = 0,
	--lightcolor = Color.white,

	--Define custom properties below
}

--Applies blockID settings
blockManager.setBlockSettings(ropeSettings)

--Register the vulnerable harm types for this Block. The first table defines the harm types the Block should be affected by, while the second maps an effect to each, if desired.

--Custom local definitions below

local ropetimer = 400
local on_rope = false


--Register events
function rope.onInitAPI()
	blockManager.registerEvent(blockID, rope, "onTickEndBlock")
	--registerEvent(rope, "onBlockHit")
end

function rope.onTickEndBlock(v)
	v.config[v.id].npcfilter = -1


    -- Don't run code for invisible entities
	if v.isHidden or v:mem(0x5A, FIELD_BOOL) then return end

	local data = v.data

	for k,p in Block.iterateIntersecting(player.x, player.y + player.height, player.x + player.width, player.y + player.height + 1) do
		if p.id == v.id and p:collidesWith(player) == 1 then

			if player.speedX == 0 and player.speedY == 0 then
				ropetimer = ropetimer - 1
			else
				ropetimer = 400
			end

			if math.abs(player.speedX) > 2 then
				player.speedX = 2 * player.direction
			end
			Defines.jumpheight = 35
		else
			Defines.jumpheight = 20
		end

		if ropetimer == 80 then
			if p:collidesWith(player) == 1 then
				player:mem(0x140, FIELD_WORD, 50)
			end
		end
	end

	if player.speedY < 0 then
		ropetimer = 400
	end
	
	if ropetimer == 0 then
		v.config[v.id].passthrough = true
	end
	
	if ropetimer == 400 and player.speedY == 0 then
		v.config[v.id].passthrough = false
	end
	end

--Gotta return the library table!
return rope
