import urllib3

from grid.cli.utilities import get_graphql_url
from grid.metadata import __version__
from grid.openapi import ApiClient, Configuration
from grid.sdk.auth import Credentials
from grid.sdk.client.grid_gql import gql_client
from grid.websocket.client import WebSocketClient
import grid.sdk.env as env


def create_gql_client(*, websocket: bool = False):
    # since we are manipulating the GRID_URL on the fly, we always need to check the env variable
    url = get_graphql_url(env.GRID_URL)
    creds = Credentials.from_locale()
    res = gql_client(url=url, creds=creds, websocket=websocket)
    return res


def create_websocket_client():
    if not env.CONTEXT:
        raise RuntimeError('Default cluster is not found. Try logging in again!')
    creds = Credentials.from_locale()
    token = urllib3.util.make_headers(basic_auth=creds.user_id + ':' + creds.api_key).get('authorization')
    return WebSocketClient(base_url=env.GRID_URL, token=token)


def create_swagger_client(check_context=True):
    """
    Create the swagger client to use the autogenerated code

    Parameters
    ----------
    check_context: bool
        If true, check if the context is set. It's only false for APIs that doesn't
        need the context information i.e login
    """
    if check_context and not env.CONTEXT:
        raise RuntimeError('Default cluster is not found. Try logging in again!')
    url = env.GRID_URL
    creds = Credentials.from_locale()
    configuration = Configuration()
    configuration.host = url
    configuration.username = creds.user_id
    configuration.password = creds.api_key
    # for custom certs we need to hint urllib to use one of them if available (requests package would use any of them). these two are also use
    # during artifacts to actually reverted and not use the custom certs if present in /grid-cli/grid/cli/cli/artifacts.py
    configuration.ssl_ca_cert = env.SSL_CA_CERT

    # TODO Increase the pool_thread (and make it configurable) and use a singleton
    api_client = ApiClient(
        configuration, header_name="Authorization", header_value=configuration.get_basic_auth_token()
    )
    api_client.user_agent = f'Grid-CLI-{__version__}'
    return api_client
