require "Ui/SixthSenseUiUtils"
require "Ui/SixthSenseUi"
local Monkey_ModData = require 'ModDataManager/Monkey_ModData';
local ModData;
local SixthSenseUtils = require "SixthSenseUtils";
local SixthSenseUiUtils = require "Ui/SixthSenseUiUtils";

if not SixthSense_UiController then
    SixthSense_UiController = {
        uiByPlayer = {},
    }
end

function SixthSense_UiController.createUi(player)
    if player:isDead() then
        return;
    end

    local ui = SixthSenseUi:new(0, 0, player:getPlayerNum())
    ui:initialise();
    ui:addToUIManager();
    SixthSense_UiController.uiByPlayer[player] = ui;

    SixthSense_UiController.applyUiOffsets();
end

function SixthSense_UiController.reloadUiPosition()
    SixthSense_UiController.applyUiOffsets();
end

function SixthSense_UiController.applyUiOffsets()
    local offsetX, offsetY = SixthSenseUiUtils.loadUiOffsets(ModData);

    local splitScreenType = SixthSenseUiUtils.getSplitScreenType();
    if splitScreenType == "CROSS" or splitScreenType == "VERTICAL" then
        offsetX = (offsetX / 2.0);
    end
    if splitScreenType == "CROSS" then
        offsetY = (offsetY / 2.0);
    end

    for p,ui in pairs(SixthSense_UiController.uiByPlayer) do
        local x = getPlayerScreenLeft(p:getPlayerNum());
        local y = getPlayerScreenTop(p:getPlayerNum());
        ui:setX(x + offsetX);
        ui:setY(y + offsetY);
    end
end

function SixthSense_UiController.removeUi(player)
    if SixthSense_UiController.uiByPlayer[player] then
        local ui = SixthSense_UiController.uiByPlayer[player];
        ui:destroyUi();
        SixthSense_UiController.uiByPlayer[player] = nil;
    end
end

function SixthSense_UiController.updateSenseInfoDisplay(player)
    if player:isDead() then
        return;
    end
    
    if not SixthSense_UiController.uiByPlayer[player] then
        SixthSense_UiController.createUi(player);
    end
   
    SixthSense_UiController.uiByPlayer[player]:updateSenseInfo(ModData.active, ModData.senseRemaining, ModData.intensity);
    SixthSense_UiController.uiByPlayer[player]:updateSenseImage();
end

local firstUpdate = true;
local hasTrait = false;
function SixthSense_UiController.onPlayerUpdate(player)
    if firstUpdate then
        local md = Monkey_ModData:initEntityModData(getPlayer(), 'SixthSense');
        ModData = md:GetMonkeyModData();
        firstUpdate = false;
    end

    if ModData.hasTrait then
        SixthSense_UiController.updateSenseInfoDisplay(player, ModData.senseRemaining, ModData.intensity);
    end
end

Events.OnPlayerUpdate.Add(SixthSense_UiController.onPlayerUpdate);
Events.OnPlayerDeath.Add(SixthSense_UiController.removeUi);
Events.OnResolutionChange.Add(SixthSense_UiController.reloadUiPosition);
Events.OnCreatePlayer.Add(SixthSense_UiController.reloadUiPosition);