from urllib.parse import urlencode


def oauth_url(client_id, permissions=None, server=None, redirect_uri=None):
    """A helper function that returns the OAuth2 URL for inviting the bot
    into servers.

    Parameters
    -----------
    client_id : str
        The client ID for your bot.
    permissions : :class:`Permissions`
        The permissions you're requesting. If not given then you won't be requesting any
        permissions.
    server : :class:`Server`
        The server to pre-select in the authorization screen, if available.
    redirect_uri : str
        An optional valid redirect URI.
    """
    url = 'https://discordapp.com/oauth2/authorize?client_id={}&scope=bot'.format(client_id)
    if permissions is not None:
        url = url + '&permissions=' + str(permissions.value)
    if server is not None:
        url = url + "&guild_id=" + server.id
    if redirect_uri is not None:
        url = url + "&response_type=code&" + urlencode({'redirect_uri': redirect_uri})
    return url