if isServer() then return; end

local Monkey_ModData = require 'ModDataManager/Monkey_ModData';
local ModData;
local SixthSenseUtils = require "SixthSenseUtils";

local DRAIN_DELTA = 0.05;
local RECHARGE_DELTA = 0.005;

local function drainSixthSense()
    if not ModData then
        return;
    end

    local modData = ModData;
    
    if modData.senseRemaining < 0 then
        modData.senseRemaining = 0;
        return;
    end

    --if no sixth sense is active, do nothing
    if not modData.active then
        return;
    end

    if modData.senseRemaining == 0 then
        SixthSenseUtils:SetActiveSixthSense(false);
        return;
    end

    if modData.senseRemaining > 0.0 then
        modData.senseRemaining = modData.senseRemaining - (DRAIN_DELTA);
    end
end

local function recoverSixthSense()
    if not ModData then
        return;
    end

    local modData = ModData;

    if modData.senseRemaining > 1 then
        modData.senseRemaining = 1;
        return;
    end

    --if sixth sense is active, do nothing
    if modData.active then
        return;
    end

    if modData.senseRemaining >= 1.0 then     
        modData.senseRemaining = 1.0;
        return;
    end

    if modData.senseRemaining < 1.0 then
        modData.senseRemaining = modData.senseRemaining + (DRAIN_DELTA);
    end
end

---- INITIALISATION ----

local firstUpdate = true;

local function OnPlayerUpdate(player)
	if firstUpdate and player == getPlayer() then
        firstUpdate = false;
        local mmd = Monkey_ModData:initEntityModData(player, 'SixthSense');
        ModData = mmd:GetMonkeyModData();
        ModData.active = ModData.active or false;
        ModData.senseRemaining = ModData.senseRemaining or 1.0;

        SixthSenseUtils:SetActiveSixthSense(false);
        Events.EveryOneMinute.Add(drainSixthSense);
        Events.EveryOneMinute.Add(recoverSixthSense);
    end

    ModData.hasTrait = SixthSenseUtils:HasTrait();
end

Events.OnPlayerUpdate.Add(OnPlayerUpdate)