#include "../../helpers/entity.lua"

paperBody = nil
arrowLocation = nil
arrow = nil
refillSound = nil
done = nil
mapMarker = nil

function init()
	paperBody = FindBody("oldnewspaper")

	SetTag(paperBody,"interact", "loc@PICK_UP")
	SetDescription(paperBody, "loc@NEWSPAPERS_BOX")

    local arrowLocation = FindLocation("arrow")
    local tr = GetLocationTransform(arrowLocation)
    arrowLTr = TransformToLocalTransform(GetBodyTransform(paperBody), tr)
    Delete(arrowLocation)
	arrow = LoadSprite("gfx/arrowdown.png")

	refillSound = LoadSound("tool_pickup.ogg")
	done = false

	mapMarker = FindBody("map")
end

function tick(dt)
	if done then return end

	drawArrow()

	if GetPlayerInteractBody() == paperBody and InputPressed("interact") then
		done = true
		RegisterTool("papergun", "PAPER_GUN", "MOD/script/missions/mission_paperboy/papergun.xml")
		SetBool("game.tool.papergun.enabled", true)
		SetInt("game.tool.papergun.ammo", 10)
		SetString("game.tool.papergun.name", "loc@PAPER_GUN")
		SetString("game.player.tool", "papergun")
		PlaySound(refillSound, GetBodyTransform(paperBody).pos)
		if IsHandleValid(paperBody) then Delete(paperBody) end
		if IsHandleValid(mapMarker) then Delete(mapMarker) end
    elseif GetBool("level.run") then
		done = cEntity:EnqueueDeletion()
		if IsHandleValid(paperBody) then Delete(paperBody) end
		if IsHandleValid(mapMarker) then Delete(mapMarker) end
	end
end


function drawArrow()
    if GetBool("game.map.enabled") then
		return
	end
	local c = GetCameraTransform().pos
    local tr = TransformToParentTransform(GetBodyTransform(paperBody), arrowLTr)
	c[2] = tr.pos[2]
	local p = VecCopy(tr.pos)
	p[2] = p[2] + math.sin(GetTime()*5)*0.3+0.3 + 2
	local t = Transform(p, QuatLookAt(tr.pos, c))
	DrawSprite(arrow, t, 2, 2, .3, .3, .3, 3, false, true)
	DrawSprite(arrow, t, 2, 2, 1, 1, 1, 1, true, true)
end
