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

amount = GetIntParam("amount", 4)
tool = GetStringParam("tool", "none")
remain = GetBoolParam("remain", false)
showArrow = GetBoolParam("show_arrow", true)

ammo = nil
refillSound = nil
sndPlay = 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
    if showArrow then
        arrow = LoadSprite("gfx/arrowdown.png")
    end
end

function getScale(t)
    local cam_pos = GetCameraTransform().pos
	t.rot = QuatLookAt(t.pos, cam_pos)
	local offset = 1.5 + math.sin(4.0*GetTime())*0.5
	t.pos[2] = t.pos[2] + offset
    local dist = VecLength(VecSub(cam_pos, t.pos))
    return math:MapRangeClamped(dist, 0, 100, 1, 8)
end

function drawArrow(t, scale)
	DrawSprite(arrow, t, scale, scale, .3, .3, .3, 3, false, true)
	DrawSprite(arrow, t, scale, scale, 1, 1, 1, 1, true, true)
end

function tick(dt)
    if not GetBool("savegame.mod.tool." .. tool .. ".enabled") and IsBodyVisible(ammo, 100) and not GetBool("game.map.enabled") then
        local tr = GetBodyTransform(ammo)
        local scale = getScale(tr)
        if showArrow then
            drawArrow(tr, scale)
        end
        if IsBodyVisible(ammo, 25) then
            DrawBodyHighlight(ammo, (1 + math.cos(4.0*GetTime()))*0.1)
        end
    end
	if ammo > 0 and GetPlayerInteractBody() == ammo and InputPressed("interact") then
		SetBool("game.tool." .. tool .. ".enabled", true)
        SetBool("savegame.mod.tool." .. tool .. ".enabled", true)
		SetString("game.player.tool", tool)
		local currentAmmo = GetInt("game.tool." .. tool .. ".ammo")
		sndPlay = PlaySound(refillSound, GetBodyTransform(ammo).pos)
		if remain then
			SetInt("game.tool." .. tool .. ".ammo", amount)
		else
			SetInt("game.tool." .. tool .. ".ammo", currentAmmo + amount)
			Delete(ammo)
            ammo = 0
            cEntity:EnqueueDeletion()
		end
	end
end
