#include "ui_defs.lua"

function Ui.NavGroup(obj)
	local navGroup = Ui.Object:new
    {
		draw = function(self)
            UiPush()
                if self.ignoreNavigation then
		    		UiIgnoreNavigation()
                end
                self.navId = UiNavGroupBegin()
                    for _,child in ipairs(self.children) do
                        child:draw()
                    end
                UiNavGroupEnd()
            UiPop()
		end
	}
	return navGroup:new(obj)
end

Ui.prevActiveElement = nil
Ui.activeElement = nil

function Ui.ProcessFocus(self)
    local child = self
    if self.ignoreNavigation then
        UiIgnoreNavigation()
    end
    child.navId = UiNavComponent(child.w, child.h)
    if UiIsComponentInFocus(child.navId) then
        if not self.hovered and Ui.activeElement and Ui.activeElement ~= child then
            Ui.activeElement:onMouseLeave()
            Ui.activeElement.hovered = false
        end
        
        if not self.hovered then
            child:onMouseEnter()
        end
        
        self.hovered = true
        if Ui.activeElement ~= child then
            Ui.prevActiveElement = Ui.activeElement
        end
        Ui.activeElement = child
        
        if InputPressed("menu_accept") and not self.onPressedOverride or InputPressed("lmb") then
            child:onPressed()
        end
    elseif self.hovered then
        self.hovered = false
        Ui.prevActiveElement = Ui.activeElement
        if Ui.activeElement == child then
            Ui.activeElement = nil
        end
        child:onMouseLeave()
    end
end

function Ui.NavComponent(obj)
    local navComponent = Ui.Object:new
    {
        id = obj.id or "navComponent",
        draw = function(self)
            Ui.ProcessFocus(self.child)
            self.child:draw()
        end,
        getSize = function(self)
            self.w,self.h = self.child:getSize()
            return self.w,self.h
        end,
    }
    local result = navComponent:new(obj)
    result.child = result.children[1]
    return result
end