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

local SixthSenseUiUtils = {}

function SixthSenseUiUtils.saveUiOffsets(x, y)
    if not ModData then
        return;
    end

	local splitScreenType = SixthSenseUiUtils.getSplitScreenType();
	if splitScreenType == "CROSS" or splitScreenType == "VERTICAL" then
		x = x * 2.0;
	end
	if splitScreenType == "CROSS" then
		y = y * 2.0;
	end

    ModData.UiOffsets = ModData.UiOffsets or {}
	local data = ModData.UiOffsets
	data.UiX = x;
	data.UiY = y;
end


function SixthSenseUiUtils.loadUiOffsets()
    if not ModData then
        return;
    end

	local BASE_UI_SIZE = 64;

    ModData.UiOffsets = ModData.UiOffsets or {}
	local data = ModData.UiOffsets
    local x = data.UiX;
    local y = data.UiY;
    if not x or not y then
    	x = 60;
    	y = 10;
    end

    local width = getCore():getScreenWidth();
    local height = getCore():getScreenHeight();

    if x + BASE_UI_SIZE > width then x = width - BASE_UI_SIZE end
    if y + BASE_UI_SIZE > height then y = height - BASE_UI_SIZE end

    return x, y;
end

function SixthSenseUiUtils.getSplitScreenType()
	local players = IsoPlayer.getPlayers();
	if players:get(1) ~= nil and players:get(2) ~= nil then
		return "CROSS";
	elseif players:get(1) ~= nil then
		return "VERTICAL";
	else
		return "NONE";
	end
end

local firstUpdate = true;

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

Events.OnPlayerUpdate.Add(onPlayerUpdate);

return SixthSenseUiUtils;