import os

import grid.cli.globals as env
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


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(os.environ.get("GRID_URL") or env.DEFAULT_GRID_URL)
    creds = Credentials.from_locale()
    res = gql_client(url=url, creds=creds, websocket=websocket)
    return res


def create_swagger_client():
    """
    Create the swagger client using the autogenerated code
    """
    url = os.environ.get("GRID_URL") or env.DEFAULT_GRID_URL.rstrip("/graphql")
    creds = Credentials.from_locale()
    configuration = Configuration()
    configuration.host = url
    configuration.username = creds.user_id
    configuration.password = creds.api_key
    # 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
