require "ui"

update = nil
protofont_surface = nil
protofont_name = nil

function mini.init()
    pal.trans(255)
    surf.cls(0)
    update = any_update
    --ui.filedialog.show(select_file)
end

function select_file(filename)
    if protofont_surface then surf.free(protofont_surface) end
    protofont_name = filename:match("([^/]+)$")
    protofont_surface = surf.loadex(filename)
end

function mini.update()
    view.origin(0,0)
    for i=0,15 do
        draw.rectf(i*8, 0, 8, 8, i)
    end
    update()
end

seltab = 1

function draw_big_char(x,y,w,h)
    if protofont_surface then
        surf.source(protofont_surface)
        for yy=0,h-1 do
            for xx=0,w-1 do
                if surf.pixel(x+xx, y+yy)~=0 then
                    draw.rectf(xx*8, yy*8, 7, 7, 0)
                else
                    draw.rectf(xx*8, yy*8, 7, 7, 12)
                end
            end
        end
    end
end

function any_update()
    surf.cls(0)

    view.origin(4,4)
    draw.rrectf(0,0,140,232,3,15)
    ui.button("NEW",4,4,30,11, {7,6,5})
    ui.button("LOAD",36,4,30,11, {9,10,11})
    ui.button("SAVE",68,4,30,11, {2,3,4})

    view.origin(8,24)
    local w,h = 128,20
    if protofont_surface then w,h = surf.size(protofont_surface) end
    draw.rrectf(0,0,132,h+35,2,14)

    draw.text("SURFACE:",4,4,12)
    if protofont_surface then
        draw.text(protofont_name,36,4,12)
        --local w,h = surf.size(protofont_surface)
        local x,y = 6,15
        surf.source(protofont_surface)
        pal.subpal(1,12)
        draw.surf(0,0,w,h,x,y,w,h)
        pal.subpal(1)
        draw.rect(x-1,y-1,w+2,h+2,0)
        draw.rrect(x-2,y-2,w+4,h+4,2,12)
        draw.text(tostring(w)..","..tostring(h), 10, 100, 3)
    else
        draw.text("<none>",36,4,12)
    end
    if ui.button("LOAD",98,20+h,30,11, {9,10,11}) then
        ui.filedialog.show(select_file)
    end


    --view.origin(4,140)
    --draw.rrectf(0,0,140,68,3,15)

    view.origin(148,4)

    draw.rrectf(0,0,21,12,3,14)
    draw.text("BASE",3,2,12)

    draw.rrectf(22,0,45,12,3,15)
    draw.text("DIACRITICS",25,2,0)
    -- acute(Á), grave(À); diaeresis(Ä), circumflex(Â); cedilla(Ç), tilde(Ñ)

    draw.rrectf(68,0,49,12,3,15)
    draw.text("PRECOMPOSED",71,2,0)

    draw.rrectf(0,8,140,140,3,14)

    view.origin(152,18)
    draw.text("CARÀCTER ACTUAL:65(A)",0,0,0)
    view.origin(152,25)
    draw_big_char(7,7,7,7)

    ui.button("<",70,2,9,9, {9,10,11})
    --draw.rrectf(80,2,16,10,2,15)
    draw.rrectf(80,2,15,9,2,13)
    draw.text("240",82,4,15)
    ui.button(">",96,2,9,9, {9,10,11})


    view.origin(152,144)
    local x,y=0,0
    for c=32,127 do
        draw.rectf(x,y,7,9,12)
        draw.rect(x,y,7,9,0)
        draw.text(string.char(c),x+2,y+2,0)
        x=x+8
        if x>=128 then
            x=0
            y=y+10
        end
    end
    draw.text("ÁÄÉÍÓÚáéíóúÀÈÌÒÙàèìòùñÑçÇ", x, y+8, 12)

end