"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""

import requests as requests_http
from .sdkconfiguration import SDKConfiguration
from formancesdkauth import utils
from formancesdkauth._hooks import AfterErrorContext, AfterSuccessContext, BeforeRequestContext, HookContext
from formancesdkauth.models import errors, operations
from jsonpath import JSONPath
from typing import Any, Dict, Optional

class Users:
    sdk_configuration: SDKConfiguration

    def __init__(self, sdk_config: SDKConfiguration) -> None:
        self.sdk_configuration = sdk_config
        
    
    
    def list(self, cursor: Optional[str] = None, page_size: Optional[int] = None, retries: Optional[utils.RetryConfig] = None) -> operations.UsersListResponse:
        hook_ctx = HookContext(operation_id='Users_list', oauth2_scopes=['auth:read'], security_source=self.sdk_configuration.security)
        request = operations.UsersListRequest(
            cursor=cursor,
            page_size=page_size,
        )
        
        base_url = utils.template_url(*self.sdk_configuration.get_server_details())
        
        url = base_url + '/api/auth/users'
        
        if callable(self.sdk_configuration.security):
            headers, query_params = utils.get_security(self.sdk_configuration.security())
        else:
            headers, query_params = utils.get_security(self.sdk_configuration.security)
        
        query_params = { **utils.get_query_params(request), **query_params }
        headers['Accept'] = 'application/json'
        headers['user-agent'] = self.sdk_configuration.user_agent
        client = self.sdk_configuration.client
        
        global_retry_config = self.sdk_configuration.retry_config
        retry_config = retries
        if retry_config is None:
            if global_retry_config:
                retry_config = global_retry_config
            else:
                retry_config = utils.RetryConfig('backoff', utils.BackoffStrategy(500, 60000, 1.5, 3600000), True)

        req = None
        def do_request():
            nonlocal req
            try:
                req = client.prepare_request(requests_http.Request('GET', url, params=query_params, headers=headers))
                req = self.sdk_configuration.get_hooks().before_request(BeforeRequestContext(hook_ctx), req)
                http_res = client.send(req)
            except Exception as e:
                _, err = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), None, e)
                if err is not None:
                    raise err from e
                raise e

            if utils.match_status_codes(['default'], http_res.status_code):
                result, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), http_res, None)
                if e is not None:
                    raise e
                if result is not None:
                    http_res = result
                else:
                    raise errors.SDKError('Unexpected error occurred', -1, '', None)
            else:
                http_res = self.sdk_configuration.get_hooks().after_success(AfterSuccessContext(hook_ctx), http_res)

            return http_res

        http_res = utils.retry(do_request, utils.Retries(retry_config, [
            '5XX'
        ]))
        
        
        def next_func() -> Optional[operations.UsersListResponse]:
            body = utils.unmarshal_json(http_res.text, Dict[Any, Any])
            next_cursor = JSONPath("$.cursor.next").parse(body)

            if len(next_cursor) == 0:
                return None
            next_cursor = next_cursor[0]
            results = JSONPath("$.cursor.data").parse(body)
            if len(results) == 0 or len(results[0]) == 0:
                return None

            return self.list(
                cursor=next_cursor,
                page_size=page_size,
                retries=retries,
            )
        
        res = operations.UsersListResponse(result=None, next=next_func)
        
        if http_res.status_code == 200:
            # pylint: disable=no-else-return
            if utils.match_content_type(http_res.headers.get('Content-Type') or '', 'application/json'):                
                out = utils.unmarshal_json(http_res.text, Optional[operations.UsersListResponseBody])
                res.result = out
            else:
                content_type = http_res.headers.get('Content-Type')
                raise errors.SDKError(f'unknown content-type received: {content_type}', http_res.status_code, http_res.text, http_res)
        else:
            raise errors.SDKError('API error occurred', http_res.status_code, http_res.text, http_res)

        return res

    
    
    def get(self, userid: str, retries: Optional[utils.RetryConfig] = None) -> operations.UsersGetResponseBody:
        hook_ctx = HookContext(operation_id='Users_get', oauth2_scopes=['auth:read'], security_source=self.sdk_configuration.security)
        request = operations.UsersGetRequest(
            userid=userid,
        )
        
        base_url = utils.template_url(*self.sdk_configuration.get_server_details())
        
        url = utils.generate_url(base_url, '/api/auth/users/{userid}', request)
        
        if callable(self.sdk_configuration.security):
            headers, query_params = utils.get_security(self.sdk_configuration.security())
        else:
            headers, query_params = utils.get_security(self.sdk_configuration.security)
        
        headers['Accept'] = 'application/json'
        headers['user-agent'] = self.sdk_configuration.user_agent
        client = self.sdk_configuration.client
        
        global_retry_config = self.sdk_configuration.retry_config
        retry_config = retries
        if retry_config is None:
            if global_retry_config:
                retry_config = global_retry_config
            else:
                retry_config = utils.RetryConfig('backoff', utils.BackoffStrategy(500, 60000, 1.5, 3600000), True)

        req = None
        def do_request():
            nonlocal req
            try:
                req = client.prepare_request(requests_http.Request('GET', url, params=query_params, headers=headers))
                req = self.sdk_configuration.get_hooks().before_request(BeforeRequestContext(hook_ctx), req)
                http_res = client.send(req)
            except Exception as e:
                _, err = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), None, e)
                if err is not None:
                    raise err from e
                raise e

            if utils.match_status_codes(['default'], http_res.status_code):
                result, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), http_res, None)
                if e is not None:
                    raise e
                if result is not None:
                    http_res = result
                else:
                    raise errors.SDKError('Unexpected error occurred', -1, '', None)
            else:
                http_res = self.sdk_configuration.get_hooks().after_success(AfterSuccessContext(hook_ctx), http_res)

            return http_res

        http_res = utils.retry(do_request, utils.Retries(retry_config, [
            '5XX'
        ]))
        
        
        
        if http_res.status_code == 200:
            # pylint: disable=no-else-return
            if utils.match_content_type(http_res.headers.get('Content-Type') or '', 'application/json'):                
                out = utils.unmarshal_json(http_res.text, Optional[operations.UsersGetResponseBody])
                return out
            
            content_type = http_res.headers.get('Content-Type')
            raise errors.SDKError(f'unknown content-type received: {content_type}', http_res.status_code, http_res.text, http_res)
        else:
            raise errors.SDKError('API error occurred', http_res.status_code, http_res.text, http_res)

    

