from typing import Optional

from cricket_cookie import env
from cricket_cookie.login import Auth
from cricket_cookie.openapi import (
    ApiClient,
    LightningappServiceApi,
    Configuration,
    AuthServiceApi,
    ClusterServiceApi,
)


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.LIGHTNING_CLOUD_URL
    configuration = Configuration()
    configuration.host = url
    # 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
    api_client = ApiClient(configuration)
    api_client.default_headers["Authorization"] = Auth().authenticate()
    api_client.user_agent = f'Grid-CLI-{env.VERSION}'
    return api_client


class GridRestClient(LightningappServiceApi, AuthServiceApi,
                     ClusterServiceApi):
    def __init__(self, api_client: Optional[ApiClient] = None):
        api_client = api_client if api_client else create_swagger_client()
        super().__init__(api_client)
