#include "game.lua"
#include "script/common.lua"
#include "helpers/entity.lua"

amount = GetIntParam("amount", 4)
tool = GetStringParam("tool", "none")
remain = GetBoolParam("remain", false)
switchTool = GetBoolParam("switch_tool", true)

ammo = nil
refillSound = nil
arrow = nil

function init()
	ammo = FindBody("ammo")
	if ammo > 0 then
        refillSound = LoadSound("tool_pickup.ogg")
		SetTag(ammo, "interact", "loc@PICK_UP")
		if gTools[tool] then
			SetDescription(ammo, gTools[tool].name)
		end
	end
	arrow = LoadSprite("gfx/arrowdown.png")
end

function drawArrow(t)
	t.rot = QuatLookAt(t.pos, GetCameraTransform().pos)
	local offset = 3.2 + math.sin(4.0*GetTime())*0.5
	t.pos[2] = t.pos[2] + offset
	DrawSprite(arrow, t, 2, 2, .3, .3, .3, 3, false, true)
	DrawSprite(arrow, t, 2, 2, 1, 1, 1, 1, true, true)
end

function tick(dt)
	if IsHandleValid(ammo) then
		if GetPlayerInteractBody() == ammo and InputPressed("interact") then
			SetBool("game.tool." .. tool .. ".enabled", true)
			if switchTool then
				SetString("game.player.tool", tool)
			end
			currentAmmo = GetInt("game.tool." .. tool .. ".ammo")
			PlaySound(refillSound, GetBodyTransform(ammo).pos)
			if remain then
				SetInt("game.tool." .. tool .. ".ammo", amount)
			else
				SetInt("game.tool." .. tool .. ".ammo", currentAmmo + amount)
				Delete(ammo)
                cEntity:EnqueueDeletion()
			end
			-- local tool_name = GetTranslatedStringByKey(GetString("game.tool." .. tool .. ".name"))
			-- local str
			-- if amount == 1 then
			-- 	str = tool_name
			-- else
			-- 	str = amount .. " x " .. tool_name
			-- end
			-- SetString("hud.hintinfo", GetTranslatedStringByKey("UI_HUD_NOTE_PICKED_UP_CUSTOM," .. str))
		else
			local p = GetPlayerTransform().pos
			local bt = GetBodyTransform(ammo)

			local dist = VecLength(VecSub(p, bt.pos))
			if dist > 4 then
				SetString("hud.hintinfo", GetTranslatedStringByKey("UI_HUD_HINT_PICK_UP_TOOLS_2"))
				drawArrow(bt)
			end
		end
	end
end
