------------------------------------------------------------------------------
-- Imports
------------------------------------------------------------------------------

local make_class = require 'src.utils.classes'
local collisions = require 'src.utils.colls'
local UIElement  = require 'src.ui.element'


------------------------------------------------------------------------------
-- Class definitions
------------------------------------------------------------------------------

local Button = make_class(UIElement)


------------------------------------------------------------------------------
-- Class methods
------------------------------------------------------------------------------

function Button:_init(x, y, callback, float)
    UIElement._init(self, x, y, float)
    self.selected    = false
    self.pressed     = false
    self.was_pressed = false
    self.callback    = callback
end


function Button:set_dimensions()
    self.w = 0
    self.h = 0
end


function Button:mousemoved(x, y)
    -- Select if the pointer is inside the button's bounding rect.
    self.selected = collisions.point_in_square(x, y, self.x, self.y, self.w, self.h)

    -- If the button was pressed then check if the pointer is no longer inside the button.
    if self.pressed then
        -- If it's not, then mark the button as "was pressed".
        self.pressed     = collisions.point_in_square(x, y, self.x, self.y, self.w, self.h)
        self.was_pressed = true
    end

    -- If the button was pressed and the pointer is inside the button right now.
    if self.was_pressed and collisions.point_in_square(x, y, self.x, self.y, self.w, self.h) then
        -- Then mark the button as pressed again.
        self.pressed     = true
        self.was_pressed = false
    end
end


function Button:mousepressed(x, y, btn)
    -- If the pointer was inside the button when it was pressed then mark the button as pressed.
    if btn == 0 then
        self.pressed = collisions.point_in_square(x, y, self.x, self.y, self.w, self.h)
    end
end


function Button:mousereleased(_, _, btn)
    if btn == 0 then
        if self.pressed then
            -- If the button was pressed then execute the callback if any and unmark as pressed.
            if self.callback ~= nil then
                self.callback()
            end

            self.pressed = false
        end

        -- The button no longer was pressed.
        self.was_pressed = false
    end
end


------------------------------------------------------------------------------
-- Module return
------------------------------------------------------------------------------

return Button
