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

local love           = require 'love'
local make_class     = require 'src.utils.classes'
local dialog_manager = require 'src.ui.dlgmngr'
local VBox           = require 'src.ui.vbox'
local Sprite         = require 'src.graphics.sprite'
local TextButton     = require 'src.ui.textbtn'
local HBox           = require 'src.ui.hbox'


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

local Dialog = make_class(VBox)


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

function Dialog:_init(bckg, spacing, padding, close_btn, accept_btn, font)
    VBox._init(self, nil, nil, nil, nil, spacing, false)
    self.spacing    = spacing ~= nil and spacing or 10
    self.padding    = padding ~= nil and padding or 15
    self.background = Sprite(bckg)
    self.shown      = false

    local close = nil

    if close_btn ~= nil then
        close = close_btn
    else
        close = TextButton(
            'Close',
            font,
            nil,
            nil,
            function()
                self:hide()
            end)
    end

    local accept = nil
    if accept_btn ~= nil then accept = accept_btn end

    -- Create a container for the close and accept button and add them.
    local box = HBox(nil, nil, nil, nil, 10, true)
    box:add(close)

    if accept ~= nil then box:add(accept) end

    self.elements[9001] = box
end


function Dialog:add(element)
    table.insert(self.elements, element)
end


function Dialog:load()
    self.background:load()
    self:set_dimensions()
    VBox.load(self)
end


function Dialog:set_dimensions()
    self.w = self.background.sprite:getWidth()
    self.h = self.background.sprite:getHeight()

    -- Center the dialog on the screen.
    self.x = (320 - self.w) / 2
    self.y = (200 - self.h) / 2

    self.background.x = self.x
    self.background.y = self.y

    -- Add padding.
    self.x = self.x + self.padding
    self.y = self.y + self.padding / 2
end


function Dialog:draw()
    love.graphics.setColor(0, 0, 0)
    love.graphics.rectangle('line', self.x - self.padding - 1, self.y - (self.padding / 2) - 1, self.w + 2, self.h + 2)
    love.graphics.setColor()

    self.background:draw()
    VBox.draw(self)
end


function Dialog:show()
    if not self.shown then
        dialog_manager:add(self)
        self.shown = true
    end
end


function Dialog:hide()
    dialog_manager:remove(self)
    self.shown = false
end


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

return Dialog
