require "LWtimer"
require "LWsettings"
require "LWtalking"

-- local conversation_timer = LWtimer:new(ZombRandFloat(5,60), false) -- Not used atm

local objectData = {} -- Combining this with other mods?

local function initZombieData(zombie)
	objectData[zombie] = {}
	local zombieData = objectData[zombie] 
	zombieData.talkTimer = LWtimer:new(ZombRandFloat(SandboxVars.LingeringVoices.LowerLineLimit, SandboxVars.LingeringVoices.UpperLineLimit), false)
end

-- Pick a random between all the types of lines.
local function getRandomLine(lines)
	
	local count = 0
	-- Get total amount of lines.
	for i,v in ipairs(lines) do
		count = count + lines[i].lineCount
	end

	local c = ZombRandBetween(1, count + 1)
	local count2 = 0
	for i,v in ipairs(lines) do 
		count2 = count2 + lines[i].lineCount
		if count2 >= c then
			return lines[i]
		end
	end
end

local function GetLinesFromState(zombie)

	local state = zombie:getCurrentState()
	
	if state == ZombieIdleState:instance() then
		return idleLines

	elseif state == LungeState:instance() then
		if ZombRandFloat(0,1) < 0.5 then 
			return lungeLines
		else 
			return idleLines
		end
	end

	if state == ThumpState:instance() then
		return thumpingLines -- Change to thump lines 
	end

	if state == AttackState:instance() then
		return attackLines
	end

	if state == FakeDeadZombieState:instance() then
		if ZombRand(1, 7) == 6 then
			return fakeDeadLines
		end
		return nil
	end
		
	return idleLines -- no special states, just speak in general.
end

local function OnZombieUpdate(zombie)

	if objectData[zombie] == nil then 
		initZombieData(zombie)
	end
	local zombieData = objectData[zombie]
	local timeToTalk = zombieData.talkTimer:tick()

	if timeToTalk then -- Talk
		local line = getRandomLine(GetLinesFromState(zombie))

		if line ~= nil then
			zombie:addLineChatElement(line:getLine())
		end
		
		zombieData.talkTimer.limit = ZombRandFloat(SandboxVars.LingeringVoices.LowerLineLimit, SandboxVars.LingeringVoices.UpperLineLimit)  -- new limit for when next line comes out
		zombieData.talkTimer.clock = 0

		if SandboxVars.LingeringVoices.RespondToSound then
			zombie:addWorldSoundUnlessInvisible(20, 50, true)			
		end
	end

end
Events.OnZombieUpdate.Add(OnZombieUpdate)

-- Respond with stagger lines when getting hit in the face.
function OnWeaponHitCharacter(wielder, victim, weapon, damage)
	if ZombRand(0, 1000) >= (1000 - SandboxVars.LingeringVoices.StaggerSpeakChance) then
		local line = getRandomLine(staggerLines)
		victim:addLineChatElement(line:getLine())

		if SandboxVars.LingeringVoices.RespondToSound then
			victim:addWorldSoundUnlessInvisible(20, 50, true)
		end
	end
end
Events.OnWeaponHitCharacter.Add(OnWeaponHitCharacter)
