-- @author DoomTero 2026
-- @copyright 2026 DoomTero - ZomboRut original work. ref:6fd3a860
-- @license Proprietary. Not licensed for reuse, redistribution or derivative works without written permission from DoomTero. Ask - permission is obtainable. See ZomboRut/LICENSE.txt

require "TimedActions/ISBaseTimedAction"
require "TimedActions/ISSubdueZombieAction"

ISUnsubdueZombieAction = ISBaseTimedAction:derive("ISUnsubdueZombieAction")

local UNSUBDUE_DURATION_TICKS = 2 * 60

function ISUnsubdueZombieAction:isValid()
	if not self.target or not self.target:isAlive() then return false end
	return self.target:getModData().zrSubdued == true
end

function ISUnsubdueZombieAction:waitToStart()
	self.character:faceThisObject(self.target)
	return self.character:shouldBeTurning()
end

function ISUnsubdueZombieAction:update()
	self.character:faceThisObject(self.target)
end

function ISUnsubdueZombieAction:start()
	self:setActionAnim("Loot")
	self:setAnimVariable("LootPosition", "Low")
end

function ISUnsubdueZombieAction:stop()
	ISBaseTimedAction.stop(self)
end

local function refundTapeCharge(inv)
	local tape = inv:getFirstTypeRecurse(ISSubdueZombieAction.ITEM_DUCT_TAPE)
	if tape and tape.getCurrentUses and tape.getMaxUses
		and tape:getCurrentUses() < tape:getMaxUses()
	then
		tape:setCurrentUses(tape:getCurrentUses() + 1)
		return
	end
	local fresh = inv:AddItem(ISSubdueZombieAction.ITEM_DUCT_TAPE)
	if fresh and fresh.setCurrentUses then fresh:setCurrentUses(1) end
end

local function bindingRefundTypes(target)
	local binding = ZR_Subdued and ZR_Subdued.getBinding and ZR_Subdued.getBinding(target)
	if binding and type(binding.types) == "table" and #binding.types > 0 then
		return binding.types
	end
	return { ISSubdueZombieAction.ITEM_ROPE }
end

function ISUnsubdueZombieAction:perform()
	local refunds = bindingRefundTypes(self.target)

	if ZR_Subdued and ZR_Subdued.release then
		ZR_Subdued.release(self.target)

		local inv = self.character:getInventory()
		if inv then
			for i = 1, #refunds do
				local t = refunds[i]
				pcall(function() inv:AddItem(t) end)
			end
			pcall(function() refundTapeCharge(inv) end)
		end
	end

	ISBaseTimedAction.perform(self)
end

function ISUnsubdueZombieAction:new(character, target)
	local o = ISBaseTimedAction.new(self, character)
	o.character    = character
	o.target       = target
	o.stopOnWalk   = true
	o.stopOnRun    = true
	o.maxTime      = UNSUBDUE_DURATION_TICKS
	o.loopedAction = false
	return o
end
