require "ui"
require "util"

msgbox = {
    title = "TITOL",
    text = { "Este es el missatge.", "Pot estar en varies linies" },
    buttons = { {"YES", sys.quit}, {"NO", app.pop} },
    selected = 0,
    w = 100,
    h = 50,
} local me = msgbox

function me.show(title, text, buttons, default)
    me.selected = default or 1
    me.title = title
    me.text = text
    me.buttons = buttons

    me.w = 0
    for i,v in ipairs(me.text) do
        local width = #v*4+8
        if width > me.w then me.w = width end
    end

    me.h = #me.text*6+35

    app.push(me.update)
end

function me.update()
    local top = (160-me.w)//2 
    local left = (104-me.h)//2
    surf.clip(top, left, me.w, me.h)
    view.origin(top, left)
    draw.rrectf(0,0,me.w, me.h,4,27)

    --draw.rectf(1,1,me.w-2, 7, 21)
    draw.text(me.title, 5, 4, 4)

    local y = 14
    for i,v in ipairs(me.text) do
        draw.text(v, 5, y, 21)
        y = y + 6
    end

    local mx, my = mouse.pos()

    local x = me.w - 35
    y = me.h - 12
    for i,v in ipairs(me.buttons) do
        ui.pushbutton(v[1],x,y,7,22,21,v[2],me.selected==i)
        x = x - 34
    end

    if key.press(key.ESCAPE) then
        app.pop()
    elseif key.press(key.RIGHT) then
        me.selected=me.selected-1
        if me.selected==0 then me.selected = #me.buttons end
    elseif key.press(key.LEFT) then
        me.selected=me.selected+1
        if me.selected>#me.buttons then me.selected = 1 end
    elseif key.press(key.RETURN) then
        me.buttons[me.selected][2]()
    end
end
