-- Original name: zNS_ReloadWeaponAction.lua
-- Original author: Nihilist Penguin (https://steamcommunity.com/id/bickback/)

-- Copyright 2023 Nihilist Penguin. This item is not authorized for posting on Steam,
-- except under the Steam account named Nihilist Penguin, or with the copyright holder's explicit permission.
-- Redistribution of this mod without explicit permission from the original creator is prohibited under any circumstances.
-- This includes, but not limited to, uploading these mods to the Steam Workshop or any other site,
-- distribution as part of another mod or modpack, and distribution of modified versions.

if not NSGlobal then
	print("NSGlobal not found, skipping zNS_ReloadWeaponAction.lua")
	return
end

local print_debug = NSGlobal.utils.register.print_debug

ISReloadWeaponAction.custom_AttackHook = function(character, chargeDelta, weapon)
	ISTimedActionQueue.clear(character)
	if character:isAttackStarted() then
		return
	end
	if instanceof(character, "IsoPlayer") and not character:isAuthorizeMeleeAction() then
		return
	end
	if weapon:isRanged() and not character:isDoShove() then
		if ISReloadWeaponAction.canShoot(weapon) then
			character:playSound(weapon:getSwingSound())

			local radius = weapon:getSoundRadius()
			local volume = weapon:getSoundVolume()
			local weapon_name = weapon:getDisplayName()

			if isClient() and SandboxVars.NS.MPRadiusNerf then
				radius = radius / 2.2
			end

			-- stylua: ignore
			print_debug("Firing " .. weapon_name .. ", Radius: " .. tostring(radius) .. " - Volume: " .. tostring(volume))

			character:addWorldSoundUnlessInvisible(radius, volume, false)

			if weapon:getCanon() then
				local canon_name = weapon:getCanon():getFullType()
				if string.sub(canon_name, 6, 13) ~= "Silencer" then
					character:startMuzzleFlash()
				end
			else
				character:startMuzzleFlash()
			end
			character:DoAttack(0)
		else
			character:DoAttack(0)
			character:setRangedWeaponEmpty(true)
		end
	-- else
	-- nerf so players in vehicles cannot use melee attacks
	elseif not character:getVehicle() or character:isDoShove() then
		ISTimedActionQueue.clear(character)
		if chargeDelta == nil then
			character:DoAttack(0)
		else
			character:DoAttack(chargeDelta)
		end
	end
end

local original_attackHook

Events.OnGameBoot.Add(function()
	Hook.Attack.Remove(ISReloadWeaponAction.attackHook)
	Hook.Attack.Add(ISReloadWeaponAction.custom_AttackHook)

	-- store the original function.
	original_attackHook = ISReloadWeaponAction.attackHook
	ISReloadWeaponAction.attackHook = ISReloadWeaponAction.custom_AttackHook
end)
