if not is_client then
    return
end

function focused(node)
    node:set_property_table("$tb_info", {
        backspace_timer = 40,
        backspace_first = true,
        cursor_timer = 30,
        cursor = nil,
        deleting = false,
    })
end

function unfocused(node)
    local info = node:get_property_table("$tb_info")
    if info.cursor ~= nil then
        local content = node:query():name("content"):matches()(nil, nil)
        content:remove_child(info.cursor)
        info.cursor = nil
    end
end

function update(node, delta)
    if node:get_property_bool("focused") then
        local txt = node:query():text():matches()(nil, nil)
        local info = node:get_property_table("$tb_info")
        if info.deleting then
            -- Always trigger on the first key press
            if info.backspace_first then
                info.backspace_first = false
                txt.text = txt.text:sub(1, -2)
            end
            -- After that wait about 80ms between deletes.
            -- The first press waits 700ms to match standard
            -- text input behaviour
            info.backspace_timer = info.backspace_timer - delta
            if info.backspace_timer <= 0 then
                txt.text = txt.text:sub(1, -2)
                info.backspace_timer = 5
            end
        else
            info.backspace_timer = 40
            info.backspace_first = true
        end

        -- Toggle the cursor to make it clear which
        -- textbox is active
        info.cursor_timer = info.cursor_timer - delta;
        if info.cursor_timer <= 0 then
            local content = node:query():name("content"):matches()(nil, nil)
            if info.cursor == nil then
                local c = ui.new("cursor")
                content:add_child(c)
                info.cursor = c
            else
                content:remove_child(info.cursor)
                info.cursor = nil
            end
            info.cursor_timer = 30
        end
    end
end

function key_down(node, evt)
    if evt.input == "Escape" then
        return false
    end
    if evt.input == "Backspace" then
        local info = node:get_property_table("$tb_info")
        info.deleting = true
    end
    return true
end

function key_up(node, evt)
    if evt.input == "Escape" then
        return false
    end
    if evt.input == "Backspace" then
        local info = node:get_property_table("$tb_info")
        info.deleting = false
    end
    return true
end
