local HEALTH_PER_METAL_RATIO = 4
local METAL_PER_HIT = 20

local lol = ents.FindByClass("worldspawn") -- worst hack ever???
local TF_TEAM_RED = 2 -- i swear TF_TEAM globals existed before the last rafmod update
local PlayerManager = ents.FindByClass("tf_player_manager")
precache.PrecacheParticle("healthgained_red_giant")
precache.PrecacheParticle("healthgained_blu_giant")

local function IsSameTeam(ent1, ent2)
	if ent1.m_iTeamNum == ent2.m_iTeamNum then
		return true
	end
	return false
end
local function TankHealParticle(tank)
	local OFFSET = Vector(0, 0, 220)
	local particleorigin = tank:GetAbsOrigin() + OFFSET
	
	particle = "healthgained_blu_giant"
	if tank.m_iTeamNum == TF_TEAM_RED then
		particle = "healthgained_red_giant"
	end
	
	util.ParticleEffect(particle, particleorigin, nil, tank)
end
local tank_dmg_callback = function(tank, damageinfo)
	local atk = damageinfo.Attacker
	local wep = damageinfo.Weapon
	local oldhealth = tank.m_iHealth 
	if IsSameTeam(atk, tank) then
		if wep ~= nil and wep:GetClassname() == "tf_weapon_wrench" and atk.m_iAmmo[TF_AMMO_METAL] > 0 or wep:GetClassname() == "tf_weapon_robot_arm" and atk.m_iAmmo[TF_AMMO_METAL] > 0 then
			local repairattribute = wep:GetAttributeValueByClass("mult_repair_value", 1)
			local oldmetal = atk.m_iAmmo[TF_AMMO_METAL]
			local newmetal = atk.m_iAmmo[TF_AMMO_METAL] - METAL_PER_HIT
			if newmetal < 0 then
				newmetal = 0
			end
			local metallost = oldmetal - newmetal
			tank.m_iHealth = tank.m_iHealth + (((metallost * HEALTH_PER_METAL_RATIO) * repairattribute) + 1)
			tank:TakeDamage({ -- make the tank take 1 damage so the healthbar updates
				Damage = 1,
				Attacker = lol,
				Weapon = lol,
			})
			if tank.m_iHealth > tank.m_iMaxHealth then
				tank.m_iHealth = tank.m_iMaxHealth
			end
			local newhealth = tank.m_iHealth
			if oldhealth < newhealth then
				atk.m_iAmmo[TF_AMMO_METAL] = newmetal
				TankHealParticle(tank)
				local healthgiven = newhealth - oldhealth
				local hudparams = {
					channel = 2,
					x = -1,
					y = 0.26,
					effect = 1,
					r1 = 0,
					g1 = 255,
					b1 = 0,
					a1 = 255,
					r2 = 0,
					holdTime = 0.5,
					fadeinTime = 0,
					fadeoutTime = 1.5,
				}
				timer.Simple(0.015, function()
					wep:AcceptInput("runscriptcode", "self.StopSound(`Weapon_Wrench.HitWorld`)")
				end)
				wep:PlaySound("Weapon_Wrench.HitBuilding_Success")
				atk:PlaySoundToSelf("Weapon_Wrench.HitBuilding_Success")
				atk:ShowHudText(hudparams, "+".. healthgiven)
			end
		end
	end
end
ents.AddCreateCallback("tank_boss", function(tank) tank:AddCallback(ON_DAMAGE_RECEIVED_PRE, tank_dmg_callback) end)