local SoundPlayer = require "SixthSenseSoundPlayer";
local SixthSenseUtils = require "SixthSenseUtils";

local MAX_INTENSITY = 0.85;
local LERP_FOR_TICKS = 50;
local DISTANCE_STATIC_MULTIPLIER = 1;
local CUTOFF_DISTANCE = 9

local tickcount = 0;
local intensity = 0;
local targetIntensity = 0;

local sound = nil;
local player;

local function checkNearbyZombies()
	local spottedList = player:getCell():getObjectList();
	local nearbyRange = 15;
	local tempdistance = 1;
	
	local nearestDistance = 9999;
	
	targetIntensity = 0;
	
	if(spottedList ~= nil) then
		for i=0, spottedList:size()-1 do
			local nearbyCharacter = spottedList:get(i);
			if(nearbyCharacter ~= nil) and (nearbyCharacter ~= player) and (instanceof(nearbyCharacter,"IsoZombie")) then
				local distance = SixthSenseUtils:GetDistanceBetween(player, nearbyCharacter);
				if distance > CUTOFF_DISTANCE then
					--targetIntensity = 0;
					--handle greater than cutoff distance
					--I know I can do this another way but it's easier to read
				elseif(distance < nearbyRange and distance < nearestDistance) then
					nearestDistance = distance;
					local tempIntensity = 1/nearestDistance;

					if(tempIntensity > MAX_INTENSITY) then
						targetIntensity = MAX_INTENSITY;
					else
						targetIntensity = tempIntensity;
					end

					targetIntensity = targetIntensity

					if targetIntensity < 0 then
						targetIntensity = 0
					end
				end
			end
		end
	end
	SixthSenseUtils:UpdateIntensity(targetIntensity);
end

local function CheckSixthSenseVicinity()	
	if not SixthSenseUtils:IsActive() or not SixthSenseUtils:HasTrait() or SixthSenseUtils:GetRemainingSense() <= 0 then
		SoundPlayer:SetStaticVolume(0);	
		targetIntensity = 0;
		SixthSenseUtils:UpdateIntensity(0);
		return;
	end

	tickcount = tickcount + 1;
	if(tickcount < LERP_FOR_TICKS) then --Lerp sixth sense intensity to target intensity on last known nearest zombie
		intensity = SixthSenseUtils:Lerp(intensity, targetIntensity, 0.2);

		SoundPlayer:SetStaticVolume(intensity * DISTANCE_STATIC_MULTIPLIER);
	else --Update nearest zombie
		tickcount = 0;
		checkNearbyZombies();
	end	
end


---- INITIALISATION ----

local firstUpdate = true;

local function OnPlayerUpdate(p)
	if firstUpdate and p == getPlayer() then
		player = getPlayer();
		Events.OnTick.Add(CheckSixthSenseVicinity);
        firstUpdate = false;
    end
end

Events.OnPlayerUpdate.Add(OnPlayerUpdate);