
local SoundPlayer = require "SixthSenseSoundPlayer";
local Monkey_ModData = require 'ModDataManager/Monkey_ModData';
local ModData;
local SixthSenseUtils = {}

local function activateSixthSense()
    local modData = ModData:GetMonkeyModData();
    if modData.senseRemaining > SixthSenseUtils:RemainingSenseMinimum() then
        local modData = ModData:GetMonkeyModData();
        modData.active = true;
    end
end

local function deactivateSixthSense()
    local modData = ModData:GetMonkeyModData();
    modData.active = false;
end

function SixthSenseUtils:SetActiveSixthSense(newState)
    if not ModData then
        return;
    end

    local modData = ModData:GetMonkeyModData();
    if newState then
        activateSixthSense(modData);
    else
        deactivateSixthSense(modData);
    end
end

function SixthSenseUtils.ToggleSixthSense()
    local modData = ModData:GetMonkeyModData();
    if modData.senseRemaining > 0 then
        local newState = not modData.active;
        SixthSenseUtils:SetActiveSixthSense(newState);
    else
        SixthSenseUtils:SetActiveSixthSense(false);
    end
end

function SixthSenseUtils:Lerp(from, to, dt)
	return (1 - dt) * from + dt * to;
end

function SixthSenseUtils:GetDistanceBetween(z1,z2)
	if(z1 == nil) or (z2 == nil) then return -1; end

	local z2z = z2:getZ();
	local z1z = z1:getZ();

	local floorDifference = math.abs(z2z - z1z);

	local z1x = z1:getX();
	local z1y = z1:getY();
	local z2x = z2:getX();
	local z2y = z2:getY();

	local dx = z1x - z2x;
	local dy = z1y - z2y;
    local dz = floorDifference * 6;

	local val = math.sqrt ((dx * dx) + (dy * dy) + (dz * dz))

	return val
end

function SixthSenseUtils:HasTrait()
    return getPlayer():HasTrait("SixthSense");
end

function SixthSenseUtils:RemainingSenseMinimum()
    return 0.25
end

function SixthSenseUtils:IsActive()
    local modData = ModData:GetMonkeyModData();
    return modData.active;
end


function SixthSenseUtils:UpdateIntensity(intensity)
    local modData = ModData:GetMonkeyModData();
    modData.intensity = intensity;
end

function SixthSenseUtils:GetRemainingSense()
    local modData = ModData:GetMonkeyModData();
    return modData.senseRemaining;
end

---- INITIALISATION ----

local firstUpdate = true;

local function OnPlayerUpdate(player)
	if firstUpdate and player == getPlayer() then
        firstUpdate = false;
        ModData = Monkey_ModData:initEntityModData(player, 'SixthSense');
    end
end

Events.OnPlayerUpdate.Add(OnPlayerUpdate)

return SixthSenseUtils;