local term = {}

function term.clear()
    coroutine.yield("VFS_write", 1, "\27C\25")
end

function term.setCursorPos(x, y)
    coroutine.yield("VFS_write", 1, "\27cs"..tostring(y)..";"..tostring(x).."\25")
end

function term.size()
    coroutine.yield("VFS_write", 1, "\27ts\25")
    local ok, data = coroutine.yield("VFS_read", 0, 16) -- read response
    if not ok then error("Failed to get terminal size") end
    local x, y = string.match(data, "%R(%d+);(%d+)\25")
    return tonumber(x), tonumber(y)
end

function term.getCursorPos()
    coroutine.yield("VFS_write", 1, "\27gc\25")
    local ok, data = coroutine.yield("VFS_read", 0, 16) -- read response
    if not ok then error("Failed to get cursor position") end
    local y, x = string.match(data, "%R(%d+);(%d+)\25")
    return tonumber(x), tonumber(y)
end

function term.write(data)
    coroutine.yield("VFS_write", 1, data)
end

function term.setTextColor(color)
    local ok, err = coroutine.yield("VFS_type", 1)
    if not ok then error(err) end
    if ok ~= "tty" then return end
    coroutine.yield("VFS_write", 1, "\27f"..tostring(color).."\25")
end

function term.setBackgroundColor(color)
    local ok, err = coroutine.yield("VFS_type", 1)
    if not ok then error(err) end
    if ok ~= "tty" then return end
    coroutine.yield("VFS_write", 1, "\27b"..tostring(color).."\25")
end

function term.isColor()
    local ok, err = coroutine.yield("VFS_type", 1)
    if not ok then error(err) end
    return ok == "tty"
end

function term.scroll(n)
    coroutine.yield("VFS_write", 1, "\27S"..tostring(n).."\25")
end

function term.setDefault(color, layer)
    if layer then
        coroutine.yield("VFS_write", 1, "\27F"..tostring(color).."\25")
    else
        coroutine.yield("VFS_write", 1, "\27B"..tostring(color).."\25")
    end
end

function term.showCursor(show)
    if show then
        coroutine.yield("VFS_write", 1, "\27sc\25")
    else
        coroutine.yield("VFS_write", 1, "\27hc\25")
    end
end

return term