#include "script/common.lua"

RADIUS = 10.0						-- Activation radius, should include all of shape with margin
TOLERANCE = 100						-- Non-yellow voxels tolerated
VALUABLE = "factory_paintboat"		-- Name of valuable
REWARD = 80							-- Cash reward

done = false

function init()
	--Find shape and all paintable voxels
	shape = FindShape("paint")
	local sx, sy, sz = GetShapeSize(shape)
	ix = {}
	iy = {}
	iz = {}
	voxelCount = 0
	for z=0, sz-1 do
		for y=0, sy-1 do
			for x=0, sx-1 do
				local t, _r, _g, _b = GetShapeMaterialAtIndex(shape, x, y, z)
				if t~="" then
					voxelCount = voxelCount + 1
					ix[voxelCount] = x
					iy[voxelCount] = y
					iz[voxelCount] = z
				end
			end
		end
	end
	snd = LoadSound("valuable.ogg")
end

function tick(dt)
	if not done then
		local mi, ma = GetShapeBounds(shape)
		local pos = VecLerp(mi, ma, 0.5)
		if VecLength(VecSub(GetPlayerTransform().pos, pos)) < RADIUS then
			local vc = GetShapeVoxelCount(shape)
			if vc < voxelCount-TOLERANCE then
				--Don't bother with broken shape
				done = true
			else
				--Count yellow voxels
				local c = 0
				for i=1, voxelCount do
					local _t, r, g, b = GetShapeMaterialAtIndex(shape, ix[i], iy[i], iz[i])
					if r > 0.6 and g > 0.6 and b < 0.4 then
						c = c + 1
					end
				end
				
				-- Check if above threshold
				if c >= voxelCount-TOLERANCE then
					--Get reward
					local v = "savegame.valuable."..VALUABLE
					if not GetBool(v) then
						PlaySound(snd)
						SetString("hud.notification", GetTranslatedStringByKey("UI_HUD_NOTE_PAYCHECK_$,"..REWARD))
						SetInt("savegame.cash", GetInt("savegame.cash")+REWARD)
						SetBool(v, true)
					end
					done = true
				end
			end
		end
	end
end

