r"""
    This code was generated by
   ___ _ _ _ _ _    _ ____    ____ ____ _    ____ ____ _  _ ____ ____ ____ ___ __   __
    |  | | | | |    | |  | __ |  | |__| | __ | __ |___ |\ | |___ |__/ |__|  | |  | |__/
    |  |_|_| | |___ | |__|    |__| |  | |    |__] |___ | \| |___ |  \ |  |  | |__| |  \

    Organization Public API
    No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)

    NOTE: This class is auto generated by OpenAPI Generator.
    https://openapi-generator.tech
    Do not edit the class manually.
"""

from datetime import datetime
from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator
from twilio.base import values
from twilio.base.api_response import ApiResponse
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.version import Version
from twilio.base.page import Page


class UserInstance(InstanceResource):

    class ScimEmailAddress(object):
        """
        :ivar primary: Indicates if this email address is the primary one
        :ivar value: The actual email address value
        :ivar type: The type of email address (e.g., work, home, etc.)
        """

        def __init__(self, payload: Dict[str, Any]):

            self.primary: Optional[bool] = payload.get("primary")
            self.value: Optional[str] = payload.get("value")
            self.type: Optional[str] = payload.get("type")

        def to_dict(self):
            return {
                "primary": self.primary,
                "value": self.value,
                "type": self.type,
            }

    class ScimMeta(object):
        """
        :ivar resource_type: Indicates the type of the resource
        :ivar created: The date and time when the resource was created in the system
        :ivar last_modified: The date and time when the resource was last modified
        :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control.
        """

        def __init__(self, payload: Dict[str, Any]):

            self.resource_type: Optional[str] = payload.get("resource_type")
            self.created: Optional[datetime] = payload.get("created")
            self.last_modified: Optional[datetime] = payload.get("last_modified")
            self.version: Optional[str] = payload.get("version")

        def to_dict(self):
            return {
                "resource_type": self.resource_type,
                "created": self.created,
                "last_modified": self.last_modified,
                "version": self.version,
            }

    class ScimName(object):
        """
        :ivar given_name: The user's first or given name
        :ivar family_name: The user's last or family name
        """

        def __init__(self, payload: Dict[str, Any]):

            self.given_name: Optional[str] = payload.get("given_name")
            self.family_name: Optional[str] = payload.get("family_name")

        def to_dict(self):
            return {
                "given_name": self.given_name,
                "family_name": self.family_name,
            }

    class ScimUser(object):
        """
        :ivar id: Unique Twilio user sid
        :ivar external_id: External unique resource id defined by provisioning client
        :ivar user_name: Unique username, MUST be same as primary email address
        :ivar display_name: User friendly display name
        :ivar name:
        :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username.
        :ivar active: Indicates whether the user is active
        :ivar locale: User's locale
        :ivar timezone: User's time zone
        :ivar schemas: An array of URIs that indicate the schemas supported for this user resource
        :ivar meta:
        :ivar detail: A human-readable description of the error
        :ivar scim_type: A scimType error code as defined in RFC7644
        :ivar status: Http status code
        :ivar code: Twilio-specific error code
        :ivar more_info: Link to Error Code References
        """

        def __init__(self, payload: Dict[str, Any]):

            self.id: Optional[str] = payload.get("id")
            self.external_id: Optional[str] = payload.get("external_id")
            self.user_name: Optional[str] = payload.get("user_name")
            self.display_name: Optional[str] = payload.get("display_name")
            self.name: Optional[UserList.ScimName] = payload.get("name")
            self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get(
                "emails"
            )
            self.active: Optional[bool] = payload.get("active")
            self.locale: Optional[str] = payload.get("locale")
            self.timezone: Optional[str] = payload.get("timezone")
            self.schemas: Optional[List[str]] = payload.get("schemas")
            self.meta: Optional[UserList.ScimMeta] = payload.get("meta")
            self.detail: Optional[str] = payload.get("detail")
            self.scim_type: Optional[str] = payload.get("scim_type")
            self.status: Optional[str] = payload.get("status")
            self.code: Optional[int] = payload.get("code")
            self.more_info: Optional[str] = payload.get("more_info")

        def to_dict(self):
            return {
                "id": self.id,
                "externalId": self.external_id,
                "userName": self.user_name,
                "displayName": self.display_name,
                "name": self.name.to_dict() if self.name is not None else None,
                "emails": (
                    [emails.to_dict() for emails in self.emails]
                    if self.emails is not None
                    else None
                ),
                "active": self.active,
                "locale": self.locale,
                "timezone": self.timezone,
                "schemas": self.schemas,
                "meta": self.meta.to_dict() if self.meta is not None else None,
                "detail": self.detail,
                "scimType": self.scim_type,
                "status": self.status,
                "code": self.code,
                "moreInfo": self.more_info,
            }

    """
    :ivar id: Unique Twilio user sid
    :ivar external_id: External unique resource id defined by provisioning client
    :ivar user_name: Unique username, MUST be same as primary email address
    :ivar display_name: User friendly display name
    :ivar name: 
    :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username.
    :ivar active: Indicates whether the user is active
    :ivar locale: User's locale
    :ivar timezone: User's time zone
    :ivar schemas: An array of URIs that indicate the schemas supported for this user resource
    :ivar meta: 
    :ivar detail: A human-readable description of the error
    :ivar scim_type: A scimType error code as defined in RFC7644
    :ivar status: Http status code
    :ivar code: Twilio-specific error code
    :ivar more_info: Link to Error Code References
    """

    def __init__(
        self,
        version: Version,
        payload: Dict[str, Any],
        organization_sid: str,
        id: Optional[str] = None,
    ):
        super().__init__(version)

        self.id: Optional[str] = payload.get("id")
        self.external_id: Optional[str] = payload.get("externalId")
        self.user_name: Optional[str] = payload.get("userName")
        self.display_name: Optional[str] = payload.get("displayName")
        self.name: Optional[UserList.str] = payload.get("name")
        self.emails: Optional[List[UserList.str]] = payload.get("emails")
        self.active: Optional[bool] = payload.get("active")
        self.locale: Optional[str] = payload.get("locale")
        self.timezone: Optional[str] = payload.get("timezone")
        self.schemas: Optional[List[str]] = payload.get("schemas")
        self.meta: Optional[UserList.str] = payload.get("meta")
        self.detail: Optional[str] = payload.get("detail")
        self.scim_type: Optional[str] = payload.get("scimType")
        self.status: Optional[str] = payload.get("status")
        self.code: Optional[int] = payload.get("code")
        self.more_info: Optional[str] = payload.get("moreInfo")

        self._solution = {
            "organization_sid": organization_sid,
            "id": id or self.id,
        }
        self._context: Optional[UserContext] = None

    @property
    def _proxy(self) -> "UserContext":
        """
        Generate an instance context for the instance, the context is capable of
        performing various actions. All instance actions are proxied to the context

        :returns: UserContext for this UserInstance
        """
        if self._context is None:
            self._context = UserContext(
                self._version,
                organization_sid=self._solution["organization_sid"],
                id=self._solution["id"],
            )
        return self._context

    def delete(self) -> bool:
        """
        Deletes the UserInstance


        :returns: True if delete succeeds, False otherwise
        """
        return self._proxy.delete()

    async def delete_async(self) -> bool:
        """
        Asynchronous coroutine that deletes the UserInstance


        :returns: True if delete succeeds, False otherwise
        """
        return await self._proxy.delete_async()

    def delete_with_http_info(self) -> ApiResponse:
        """
        Deletes the UserInstance with HTTP info


        :returns: ApiResponse with success boolean, status code, and headers
        """
        return self._proxy.delete_with_http_info()

    async def delete_with_http_info_async(self) -> ApiResponse:
        """
        Asynchronous coroutine that deletes the UserInstance with HTTP info


        :returns: ApiResponse with success boolean, status code, and headers
        """
        return await self._proxy.delete_with_http_info_async()

    def fetch(self) -> "UserInstance":
        """
        Fetch the UserInstance


        :returns: The fetched UserInstance
        """
        return self._proxy.fetch()

    async def fetch_async(self) -> "UserInstance":
        """
        Asynchronous coroutine to fetch the UserInstance


        :returns: The fetched UserInstance
        """
        return await self._proxy.fetch_async()

    def fetch_with_http_info(self) -> ApiResponse:
        """
        Fetch the UserInstance with HTTP info


        :returns: ApiResponse with instance, status code, and headers
        """
        return self._proxy.fetch_with_http_info()

    async def fetch_with_http_info_async(self) -> ApiResponse:
        """
        Asynchronous coroutine to fetch the UserInstance with HTTP info


        :returns: ApiResponse with instance, status code, and headers
        """
        return await self._proxy.fetch_with_http_info_async()

    def update(
        self, scim_user: ScimUser, if_match: Union[str, object] = values.unset
    ) -> "UserInstance":
        """
        Update the UserInstance

        :param scim_user:
        :param if_match:

        :returns: The updated UserInstance
        """
        return self._proxy.update(
            scim_user=scim_user,
            if_match=if_match,
        )

    async def update_async(
        self, scim_user: ScimUser, if_match: Union[str, object] = values.unset
    ) -> "UserInstance":
        """
        Asynchronous coroutine to update the UserInstance

        :param scim_user:
        :param if_match:

        :returns: The updated UserInstance
        """
        return await self._proxy.update_async(
            scim_user=scim_user,
            if_match=if_match,
        )

    def update_with_http_info(
        self, scim_user: ScimUser, if_match: Union[str, object] = values.unset
    ) -> ApiResponse:
        """
        Update the UserInstance with HTTP info

        :param scim_user:
        :param if_match:

        :returns: ApiResponse with instance, status code, and headers
        """
        return self._proxy.update_with_http_info(
            scim_user=scim_user,
            if_match=if_match,
        )

    async def update_with_http_info_async(
        self, scim_user: ScimUser, if_match: Union[str, object] = values.unset
    ) -> ApiResponse:
        """
        Asynchronous coroutine to update the UserInstance with HTTP info

        :param scim_user:
        :param if_match:

        :returns: ApiResponse with instance, status code, and headers
        """
        return await self._proxy.update_with_http_info_async(
            scim_user=scim_user,
            if_match=if_match,
        )

    def __repr__(self) -> str:
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        """
        context = " ".join("{}={}".format(k, v) for k, v in self._solution.items())
        return "<Twilio.PreviewIam.Versionless.UserInstance {}>".format(context)


class UserContext(InstanceContext):

    class ScimEmailAddress(object):
        """
        :ivar primary: Indicates if this email address is the primary one
        :ivar value: The actual email address value
        :ivar type: The type of email address (e.g., work, home, etc.)
        """

        def __init__(self, payload: Dict[str, Any]):

            self.primary: Optional[bool] = payload.get("primary")
            self.value: Optional[str] = payload.get("value")
            self.type: Optional[str] = payload.get("type")

        def to_dict(self):
            return {
                "primary": self.primary,
                "value": self.value,
                "type": self.type,
            }

    class ScimMeta(object):
        """
        :ivar resource_type: Indicates the type of the resource
        :ivar created: The date and time when the resource was created in the system
        :ivar last_modified: The date and time when the resource was last modified
        :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control.
        """

        def __init__(self, payload: Dict[str, Any]):

            self.resource_type: Optional[str] = payload.get("resource_type")
            self.created: Optional[datetime] = payload.get("created")
            self.last_modified: Optional[datetime] = payload.get("last_modified")
            self.version: Optional[str] = payload.get("version")

        def to_dict(self):
            return {
                "resource_type": self.resource_type,
                "created": self.created,
                "last_modified": self.last_modified,
                "version": self.version,
            }

    class ScimName(object):
        """
        :ivar given_name: The user's first or given name
        :ivar family_name: The user's last or family name
        """

        def __init__(self, payload: Dict[str, Any]):

            self.given_name: Optional[str] = payload.get("given_name")
            self.family_name: Optional[str] = payload.get("family_name")

        def to_dict(self):
            return {
                "given_name": self.given_name,
                "family_name": self.family_name,
            }

    class ScimUser(object):
        """
        :ivar id: Unique Twilio user sid
        :ivar external_id: External unique resource id defined by provisioning client
        :ivar user_name: Unique username, MUST be same as primary email address
        :ivar display_name: User friendly display name
        :ivar name:
        :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username.
        :ivar active: Indicates whether the user is active
        :ivar locale: User's locale
        :ivar timezone: User's time zone
        :ivar schemas: An array of URIs that indicate the schemas supported for this user resource
        :ivar meta:
        :ivar detail: A human-readable description of the error
        :ivar scim_type: A scimType error code as defined in RFC7644
        :ivar status: Http status code
        :ivar code: Twilio-specific error code
        :ivar more_info: Link to Error Code References
        """

        def __init__(self, payload: Dict[str, Any]):

            self.id: Optional[str] = payload.get("id")
            self.external_id: Optional[str] = payload.get("external_id")
            self.user_name: Optional[str] = payload.get("user_name")
            self.display_name: Optional[str] = payload.get("display_name")
            self.name: Optional[UserList.ScimName] = payload.get("name")
            self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get(
                "emails"
            )
            self.active: Optional[bool] = payload.get("active")
            self.locale: Optional[str] = payload.get("locale")
            self.timezone: Optional[str] = payload.get("timezone")
            self.schemas: Optional[List[str]] = payload.get("schemas")
            self.meta: Optional[UserList.ScimMeta] = payload.get("meta")
            self.detail: Optional[str] = payload.get("detail")
            self.scim_type: Optional[str] = payload.get("scim_type")
            self.status: Optional[str] = payload.get("status")
            self.code: Optional[int] = payload.get("code")
            self.more_info: Optional[str] = payload.get("more_info")

        def to_dict(self):
            return {
                "id": self.id,
                "externalId": self.external_id,
                "userName": self.user_name,
                "displayName": self.display_name,
                "name": self.name.to_dict() if self.name is not None else None,
                "emails": (
                    [emails.to_dict() for emails in self.emails]
                    if self.emails is not None
                    else None
                ),
                "active": self.active,
                "locale": self.locale,
                "timezone": self.timezone,
                "schemas": self.schemas,
                "meta": self.meta.to_dict() if self.meta is not None else None,
                "detail": self.detail,
                "scimType": self.scim_type,
                "status": self.status,
                "code": self.code,
                "moreInfo": self.more_info,
            }

    def __init__(self, version: Version, organization_sid: str, id: str):
        """
        Initialize the UserContext

        :param version: Version that contains the resource
        :param organization_sid:
        :param id:
        """
        super().__init__(version)

        # Path Solution
        self._solution = {
            "organization_sid": organization_sid,
            "id": id,
        }
        self._uri = "/{organization_sid}/scim/Users/{id}".format(**self._solution)

    def _delete(self) -> tuple:
        """
        Internal helper for delete operation

        Returns:
            tuple: (success_boolean, status_code, headers)
        """

        headers = values.of({})

        headers["Accept"] = "application/scim+json"

        return self._version.delete_with_response_info(
            method="DELETE", uri=self._uri, headers=headers
        )

    def delete(self) -> bool:
        """
        Deletes the UserInstance


        :returns: True if delete succeeds, False otherwise
        """
        success, _, _ = self._delete()
        return success

    def delete_with_http_info(self) -> ApiResponse:
        """
        Deletes the UserInstance and return response metadata


        :returns: ApiResponse with success boolean, status code, and headers
        """
        success, status_code, headers = self._delete()
        return ApiResponse(data=success, status_code=status_code, headers=headers)

    async def _delete_async(self) -> tuple:
        """
        Internal async helper for delete operation

        Returns:
            tuple: (success_boolean, status_code, headers)
        """

        headers = values.of({})

        headers["Accept"] = "application/scim+json"

        return await self._version.delete_with_response_info_async(
            method="DELETE", uri=self._uri, headers=headers
        )

    async def delete_async(self) -> bool:
        """
        Asynchronous coroutine that deletes the UserInstance


        :returns: True if delete succeeds, False otherwise
        """
        success, _, _ = await self._delete_async()
        return success

    async def delete_with_http_info_async(self) -> ApiResponse:
        """
        Asynchronous coroutine that deletes the UserInstance and return response metadata


        :returns: ApiResponse with success boolean, status code, and headers
        """
        success, status_code, headers = await self._delete_async()
        return ApiResponse(data=success, status_code=status_code, headers=headers)

    def _fetch(self) -> tuple:
        """
        Internal helper for fetch operation

        Returns:
            tuple: (payload, status_code, headers)
        """

        headers = values.of({})

        headers["Accept"] = "application/scim+json"

        return self._version.fetch_with_response_info(
            method="GET", uri=self._uri, headers=headers
        )

    def fetch(self) -> UserInstance:
        """
        Fetch the UserInstance


        :returns: The fetched UserInstance
        """
        payload, _, _ = self._fetch()
        return UserInstance(
            self._version,
            payload,
            organization_sid=self._solution["organization_sid"],
            id=self._solution["id"],
        )

    def fetch_with_http_info(self) -> ApiResponse:
        """
        Fetch the UserInstance and return response metadata


        :returns: ApiResponse with instance, status code, and headers
        """
        payload, status_code, headers = self._fetch()
        instance = UserInstance(
            self._version,
            payload,
            organization_sid=self._solution["organization_sid"],
            id=self._solution["id"],
        )
        return ApiResponse(data=instance, status_code=status_code, headers=headers)

    async def _fetch_async(self) -> tuple:
        """
        Internal async helper for fetch operation

        Returns:
            tuple: (payload, status_code, headers)
        """

        headers = values.of({})

        headers["Accept"] = "application/scim+json"

        return await self._version.fetch_with_response_info_async(
            method="GET", uri=self._uri, headers=headers
        )

    async def fetch_async(self) -> UserInstance:
        """
        Asynchronous coroutine to fetch the UserInstance


        :returns: The fetched UserInstance
        """
        payload, _, _ = await self._fetch_async()
        return UserInstance(
            self._version,
            payload,
            organization_sid=self._solution["organization_sid"],
            id=self._solution["id"],
        )

    async def fetch_with_http_info_async(self) -> ApiResponse:
        """
        Asynchronous coroutine to fetch the UserInstance and return response metadata


        :returns: ApiResponse with instance, status code, and headers
        """
        payload, status_code, headers = await self._fetch_async()
        instance = UserInstance(
            self._version,
            payload,
            organization_sid=self._solution["organization_sid"],
            id=self._solution["id"],
        )
        return ApiResponse(data=instance, status_code=status_code, headers=headers)

    def _update(
        self, scim_user: ScimUser, if_match: Union[str, object] = values.unset
    ) -> tuple:
        """
        Internal helper for update operation

        Returns:
            tuple: (payload, status_code, headers)
        """
        data = scim_user.to_dict()

        headers = values.of({})

        if not (
            if_match is values.unset or (isinstance(if_match, str) and not if_match)
        ):
            headers["If-Match"] = if_match

        headers["Content-Type"] = "application/json"

        headers["Content-Type"] = "application/scim+json"

        headers["Accept"] = "application/scim+json"

        return self._version.update_with_response_info(
            method="PUT", uri=self._uri, data=data, headers=headers
        )

    def update(
        self, scim_user: ScimUser, if_match: Union[str, object] = values.unset
    ) -> UserInstance:
        """
        Update the UserInstance

        :param scim_user:
        :param if_match:

        :returns: The updated UserInstance
        """
        payload, _, _ = self._update(scim_user=scim_user, if_match=if_match)
        return UserInstance(
            self._version,
            payload,
            organization_sid=self._solution["organization_sid"],
            id=self._solution["id"],
        )

    def update_with_http_info(
        self, scim_user: ScimUser, if_match: Union[str, object] = values.unset
    ) -> ApiResponse:
        """
        Update the UserInstance and return response metadata

        :param scim_user:
        :param if_match:

        :returns: ApiResponse with instance, status code, and headers
        """
        payload, status_code, headers = self._update(
            scim_user=scim_user, if_match=if_match
        )
        instance = UserInstance(
            self._version,
            payload,
            organization_sid=self._solution["organization_sid"],
            id=self._solution["id"],
        )
        return ApiResponse(data=instance, status_code=status_code, headers=headers)

    async def _update_async(
        self, scim_user: ScimUser, if_match: Union[str, object] = values.unset
    ) -> tuple:
        """
        Internal async helper for update operation

        Returns:
            tuple: (payload, status_code, headers)
        """
        data = scim_user.to_dict()

        headers = values.of({})

        if not (
            if_match is values.unset or (isinstance(if_match, str) and not if_match)
        ):
            headers["If-Match"] = if_match

        headers["Content-Type"] = "application/json"

        headers["Content-Type"] = "application/scim+json"

        headers["Accept"] = "application/scim+json"

        return await self._version.update_with_response_info_async(
            method="PUT", uri=self._uri, data=data, headers=headers
        )

    async def update_async(
        self, scim_user: ScimUser, if_match: Union[str, object] = values.unset
    ) -> UserInstance:
        """
        Asynchronous coroutine to update the UserInstance

        :param scim_user:
        :param if_match:

        :returns: The updated UserInstance
        """
        payload, _, _ = await self._update_async(scim_user=scim_user, if_match=if_match)
        return UserInstance(
            self._version,
            payload,
            organization_sid=self._solution["organization_sid"],
            id=self._solution["id"],
        )

    async def update_with_http_info_async(
        self, scim_user: ScimUser, if_match: Union[str, object] = values.unset
    ) -> ApiResponse:
        """
        Asynchronous coroutine to update the UserInstance and return response metadata

        :param scim_user:
        :param if_match:

        :returns: ApiResponse with instance, status code, and headers
        """
        payload, status_code, headers = await self._update_async(
            scim_user=scim_user, if_match=if_match
        )
        instance = UserInstance(
            self._version,
            payload,
            organization_sid=self._solution["organization_sid"],
            id=self._solution["id"],
        )
        return ApiResponse(data=instance, status_code=status_code, headers=headers)

    def __repr__(self) -> str:
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        """
        context = " ".join("{}={}".format(k, v) for k, v in self._solution.items())
        return "<Twilio.PreviewIam.Versionless.UserContext {}>".format(context)


class UserPage(Page):

    def get_instance(self, payload: Dict[str, Any]) -> UserInstance:
        """
        Build an instance of UserInstance

        :param payload: Payload response from the API
        """
        return UserInstance(
            self._version, payload, organization_sid=self._solution["organization_sid"]
        )

    def __repr__(self) -> str:
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        """
        return "<Twilio.PreviewIam.Versionless.UserPage>"


class UserList(ListResource):

    class ScimEmailAddress(object):
        """
        :ivar primary: Indicates if this email address is the primary one
        :ivar value: The actual email address value
        :ivar type: The type of email address (e.g., work, home, etc.)
        """

        def __init__(self, payload: Dict[str, Any]):

            self.primary: Optional[bool] = payload.get("primary")
            self.value: Optional[str] = payload.get("value")
            self.type: Optional[str] = payload.get("type")

        def to_dict(self):
            return {
                "primary": self.primary,
                "value": self.value,
                "type": self.type,
            }

    class ScimMeta(object):
        """
        :ivar resource_type: Indicates the type of the resource
        :ivar created: The date and time when the resource was created in the system
        :ivar last_modified: The date and time when the resource was last modified
        :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control.
        """

        def __init__(self, payload: Dict[str, Any]):

            self.resource_type: Optional[str] = payload.get("resource_type")
            self.created: Optional[datetime] = payload.get("created")
            self.last_modified: Optional[datetime] = payload.get("last_modified")
            self.version: Optional[str] = payload.get("version")

        def to_dict(self):
            return {
                "resource_type": self.resource_type,
                "created": self.created,
                "last_modified": self.last_modified,
                "version": self.version,
            }

    class ScimName(object):
        """
        :ivar given_name: The user's first or given name
        :ivar family_name: The user's last or family name
        """

        def __init__(self, payload: Dict[str, Any]):

            self.given_name: Optional[str] = payload.get("given_name")
            self.family_name: Optional[str] = payload.get("family_name")

        def to_dict(self):
            return {
                "given_name": self.given_name,
                "family_name": self.family_name,
            }

    class ScimUser(object):
        """
        :ivar id: Unique Twilio user sid
        :ivar external_id: External unique resource id defined by provisioning client
        :ivar user_name: Unique username, MUST be same as primary email address
        :ivar display_name: User friendly display name
        :ivar name:
        :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username.
        :ivar active: Indicates whether the user is active
        :ivar locale: User's locale
        :ivar timezone: User's time zone
        :ivar schemas: An array of URIs that indicate the schemas supported for this user resource
        :ivar meta:
        :ivar detail: A human-readable description of the error
        :ivar scim_type: A scimType error code as defined in RFC7644
        :ivar status: Http status code
        :ivar code: Twilio-specific error code
        :ivar more_info: Link to Error Code References
        """

        def __init__(self, payload: Dict[str, Any]):

            self.id: Optional[str] = payload.get("id")
            self.external_id: Optional[str] = payload.get("external_id")
            self.user_name: Optional[str] = payload.get("user_name")
            self.display_name: Optional[str] = payload.get("display_name")
            self.name: Optional[UserList.ScimName] = payload.get("name")
            self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get(
                "emails"
            )
            self.active: Optional[bool] = payload.get("active")
            self.locale: Optional[str] = payload.get("locale")
            self.timezone: Optional[str] = payload.get("timezone")
            self.schemas: Optional[List[str]] = payload.get("schemas")
            self.meta: Optional[UserList.ScimMeta] = payload.get("meta")
            self.detail: Optional[str] = payload.get("detail")
            self.scim_type: Optional[str] = payload.get("scim_type")
            self.status: Optional[str] = payload.get("status")
            self.code: Optional[int] = payload.get("code")
            self.more_info: Optional[str] = payload.get("more_info")

        def to_dict(self):
            return {
                "id": self.id,
                "externalId": self.external_id,
                "userName": self.user_name,
                "displayName": self.display_name,
                "name": self.name.to_dict() if self.name is not None else None,
                "emails": (
                    [emails.to_dict() for emails in self.emails]
                    if self.emails is not None
                    else None
                ),
                "active": self.active,
                "locale": self.locale,
                "timezone": self.timezone,
                "schemas": self.schemas,
                "meta": self.meta.to_dict() if self.meta is not None else None,
                "detail": self.detail,
                "scimType": self.scim_type,
                "status": self.status,
                "code": self.code,
                "moreInfo": self.more_info,
            }

    def __init__(self, version: Version, organization_sid: str):
        """
        Initialize the UserList

        :param version: Version that contains the resource
        :param organization_sid:

        """
        super().__init__(version)

        # Path Solution
        self._solution = {
            "organization_sid": organization_sid,
        }
        self._uri = "/{organization_sid}/scim/Users".format(**self._solution)

    def _create(self, scim_user: ScimUser) -> tuple:
        """
        Internal helper for create operation

        Returns:
            tuple: (payload, status_code, headers)
        """
        data = scim_user.to_dict()

        headers = values.of({"Content-Type": "application/x-www-form-urlencoded"})

        headers["Content-Type"] = "application/json"

        headers["Content-Type"] = "application/scim+json"

        headers["Accept"] = "application/scim+json"

        return self._version.create_with_response_info(
            method="POST", uri=self._uri, data=data, headers=headers
        )

    def create(self, scim_user: ScimUser) -> UserInstance:
        """
        Create the UserInstance

        :param scim_user:

        :returns: The created UserInstance
        """
        payload, _, _ = self._create(scim_user=scim_user)
        return UserInstance(
            self._version, payload, organization_sid=self._solution["organization_sid"]
        )

    def create_with_http_info(self, scim_user: ScimUser) -> ApiResponse:
        """
        Create the UserInstance and return response metadata

        :param scim_user:

        :returns: ApiResponse with instance, status code, and headers
        """
        payload, status_code, headers = self._create(scim_user=scim_user)
        instance = UserInstance(
            self._version, payload, organization_sid=self._solution["organization_sid"]
        )
        return ApiResponse(data=instance, status_code=status_code, headers=headers)

    async def _create_async(self, scim_user: ScimUser) -> tuple:
        """
        Internal async helper for create operation

        Returns:
            tuple: (payload, status_code, headers)
        """
        data = scim_user.to_dict()

        headers = values.of({"Content-Type": "application/x-www-form-urlencoded"})

        headers["Content-Type"] = "application/json"

        headers["Content-Type"] = "application/scim+json"

        headers["Accept"] = "application/scim+json"

        return await self._version.create_with_response_info_async(
            method="POST", uri=self._uri, data=data, headers=headers
        )

    async def create_async(self, scim_user: ScimUser) -> UserInstance:
        """
        Asynchronously create the UserInstance

        :param scim_user:

        :returns: The created UserInstance
        """
        payload, _, _ = await self._create_async(scim_user=scim_user)
        return UserInstance(
            self._version, payload, organization_sid=self._solution["organization_sid"]
        )

    async def create_with_http_info_async(self, scim_user: ScimUser) -> ApiResponse:
        """
        Asynchronously create the UserInstance and return response metadata

        :param scim_user:

        :returns: ApiResponse with instance, status code, and headers
        """
        payload, status_code, headers = await self._create_async(scim_user=scim_user)
        instance = UserInstance(
            self._version, payload, organization_sid=self._solution["organization_sid"]
        )
        return ApiResponse(data=instance, status_code=status_code, headers=headers)

    def stream(
        self,
        filter: Union[str, object] = values.unset,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> Iterator[UserInstance]:
        """
        Streams UserInstance records from the API as a generator stream.
        This operation lazily loads records as efficiently as possible until the limit
        is reached.
        The results are returned as a generator, so this operation is memory efficient.

        :param str filter:
        :param limit: Upper limit for the number of records to return. stream()
                      guarantees to never return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, stream() will attempt to read the
                          limit with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        """
        limits = self._version.read_limits(limit, page_size)
        page = self.page(filter=filter, page_size=limits["page_size"])

        return self._version.stream(page, limits["limit"])

    async def stream_async(
        self,
        filter: Union[str, object] = values.unset,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> AsyncIterator[UserInstance]:
        """
        Asynchronously streams UserInstance records from the API as a generator stream.
        This operation lazily loads records as efficiently as possible until the limit
        is reached.
        The results are returned as a generator, so this operation is memory efficient.

        :param str filter:
        :param limit: Upper limit for the number of records to return. stream()
                      guarantees to never return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, stream() will attempt to read the
                          limit with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        """
        limits = self._version.read_limits(limit, page_size)
        page = await self.page_async(filter=filter, page_size=limits["page_size"])

        return self._version.stream_async(page, limits["limit"])

    def stream_with_http_info(
        self,
        filter: Union[str, object] = values.unset,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> tuple:
        """
        Streams UserInstance and returns headers from first page


        :param str filter:
        :param limit: Upper limit for the number of records to return. stream()
                      guarantees to never return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, stream() will attempt to read the
                          limit with the most efficient page size, i.e. min(limit, 1000)

        :returns: tuple of (generator, status_code, headers) where generator yields instances
        """
        limits = self._version.read_limits(limit, page_size)
        page_response = self.page_with_http_info(
            filter=filter, page_size=limits["page_size"]
        )

        generator = self._version.stream(page_response.data, limits["limit"])
        return (generator, page_response.status_code, page_response.headers)

    async def stream_with_http_info_async(
        self,
        filter: Union[str, object] = values.unset,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> tuple:
        """
        Asynchronously streams UserInstance and returns headers from first page


        :param str filter:
        :param limit: Upper limit for the number of records to return. stream()
                      guarantees to never return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, stream() will attempt to read the
                          limit with the most efficient page size, i.e. min(limit, 1000)

        :returns: tuple of (generator, status_code, headers) where generator yields instances
        """
        limits = self._version.read_limits(limit, page_size)
        page_response = await self.page_with_http_info_async(
            filter=filter, page_size=limits["page_size"]
        )

        generator = self._version.stream_async(page_response.data, limits["limit"])
        return (generator, page_response.status_code, page_response.headers)

    def list(
        self,
        filter: Union[str, object] = values.unset,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> List[UserInstance]:
        """
        Lists UserInstance records from the API as a list.
        Unlike stream(), this operation is eager and will load `limit` records into
        memory before returning.

        :param str filter:
        :param limit: Upper limit for the number of records to return. list() guarantees
                      never to return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, list() will attempt to read the limit
                          with the most efficient page size, i.e. min(limit, 1000)

        :returns: list that will contain up to limit results
        """
        return list(
            self.stream(
                filter=filter,
                limit=limit,
                page_size=page_size,
            )
        )

    async def list_async(
        self,
        filter: Union[str, object] = values.unset,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> List[UserInstance]:
        """
        Asynchronously lists UserInstance records from the API as a list.
        Unlike stream(), this operation is eager and will load `limit` records into
        memory before returning.

        :param str filter:
        :param limit: Upper limit for the number of records to return. list() guarantees
                      never to return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, list() will attempt to read the limit
                          with the most efficient page size, i.e. min(limit, 1000)

        :returns: list that will contain up to limit results
        """
        return [
            record
            async for record in await self.stream_async(
                filter=filter,
                limit=limit,
                page_size=page_size,
            )
        ]

    def list_with_http_info(
        self,
        filter: Union[str, object] = values.unset,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> ApiResponse:
        """
        Lists UserInstance and returns headers from first page


        :param str filter:
        :param limit: Upper limit for the number of records to return. list() guarantees
                      never to return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, list() will attempt to read the limit
                          with the most efficient page size, i.e. min(limit, 1000)

        :returns: ApiResponse with list of instances, status code, and headers
        """
        generator, status_code, headers = self.stream_with_http_info(
            filter=filter,
            limit=limit,
            page_size=page_size,
        )
        items = list(generator)
        return ApiResponse(data=items, status_code=status_code, headers=headers)

    async def list_with_http_info_async(
        self,
        filter: Union[str, object] = values.unset,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> ApiResponse:
        """
        Asynchronously lists UserInstance and returns headers from first page


        :param str filter:
        :param limit: Upper limit for the number of records to return. list() guarantees
                      never to return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, list() will attempt to read the limit
                          with the most efficient page size, i.e. min(limit, 1000)

        :returns: ApiResponse with list of instances, status code, and headers
        """
        generator, status_code, headers = await self.stream_with_http_info_async(
            filter=filter,
            limit=limit,
            page_size=page_size,
        )
        items = [record async for record in generator]
        return ApiResponse(data=items, status_code=status_code, headers=headers)

    def page(
        self,
        filter: Union[str, object] = values.unset,
        page_token: Union[str, object] = values.unset,
        page_number: Union[int, object] = values.unset,
        page_size: Union[int, object] = values.unset,
    ) -> UserPage:
        """
        Retrieve a single page of UserInstance records from the API.
        Request is executed immediately

        :param filter:
        :param page_token: PageToken provided by the API
        :param page_number: Page Number, this value is simply for client state
        :param page_size: Number of records to return, defaults to 50

        :returns: Page of UserInstance
        """
        data = values.of(
            {
                "filter": filter,
                "PageToken": page_token,
                "Page": page_number,
                "PageSize": page_size,
            }
        )

        headers = values.of({"Content-Type": "application/x-www-form-urlencoded"})

        headers["Accept"] = "application/scim+json"

        response = self._version.page(
            method="GET", uri=self._uri, params=data, headers=headers
        )
        return UserPage(self._version, response, self._solution)

    async def page_async(
        self,
        filter: Union[str, object] = values.unset,
        page_token: Union[str, object] = values.unset,
        page_number: Union[int, object] = values.unset,
        page_size: Union[int, object] = values.unset,
    ) -> UserPage:
        """
        Asynchronously retrieve a single page of UserInstance records from the API.
        Request is executed immediately

        :param filter:
        :param page_token: PageToken provided by the API
        :param page_number: Page Number, this value is simply for client state
        :param page_size: Number of records to return, defaults to 50

        :returns: Page of UserInstance
        """
        data = values.of(
            {
                "filter": filter,
                "PageToken": page_token,
                "Page": page_number,
                "PageSize": page_size,
            }
        )

        headers = values.of({"Content-Type": "application/x-www-form-urlencoded"})

        headers["Accept"] = "application/scim+json"

        response = await self._version.page_async(
            method="GET", uri=self._uri, params=data, headers=headers
        )
        return UserPage(self._version, response, self._solution)

    def page_with_http_info(
        self,
        filter: Union[str, object] = values.unset,
        page_token: Union[str, object] = values.unset,
        page_number: Union[int, object] = values.unset,
        page_size: Union[int, object] = values.unset,
    ) -> ApiResponse:
        """
        Retrieve a single page with response metadata


        :param filter:
        :param page_token: PageToken provided by the API
        :param page_number: Page Number, this value is simply for client state
        :param page_size: Number of records to return, defaults to 50

        :returns: ApiResponse with UserPage, status code, and headers
        """
        data = values.of(
            {
                "filter": filter,
                "PageToken": page_token,
                "Page": page_number,
                "PageSize": page_size,
            }
        )

        headers = values.of({"Content-Type": "application/x-www-form-urlencoded"})

        headers["Accept"] = "application/scim+json"

        response, status_code, response_headers = self._version.page_with_response_info(
            method="GET", uri=self._uri, params=data, headers=headers
        )
        page = UserPage(self._version, response, self._solution)
        return ApiResponse(data=page, status_code=status_code, headers=response_headers)

    async def page_with_http_info_async(
        self,
        filter: Union[str, object] = values.unset,
        page_token: Union[str, object] = values.unset,
        page_number: Union[int, object] = values.unset,
        page_size: Union[int, object] = values.unset,
    ) -> ApiResponse:
        """
        Asynchronously retrieve a single page with response metadata


        :param filter:
        :param page_token: PageToken provided by the API
        :param page_number: Page Number, this value is simply for client state
        :param page_size: Number of records to return, defaults to 50

        :returns: ApiResponse with UserPage, status code, and headers
        """
        data = values.of(
            {
                "filter": filter,
                "PageToken": page_token,
                "Page": page_number,
                "PageSize": page_size,
            }
        )

        headers = values.of({"Content-Type": "application/x-www-form-urlencoded"})

        headers["Accept"] = "application/scim+json"

        response, status_code, response_headers = (
            await self._version.page_with_response_info_async(
                method="GET", uri=self._uri, params=data, headers=headers
            )
        )
        page = UserPage(self._version, response, self._solution)
        return ApiResponse(data=page, status_code=status_code, headers=response_headers)

    def get_page(self, target_url: str) -> UserPage:
        """
        Retrieve a specific page of UserInstance records from the API.
        Request is executed immediately

        :param target_url: API-generated URL for the requested results page

        :returns: Page of UserInstance
        """
        response = self._version.domain.twilio.request("GET", target_url)
        return UserPage(self._version, response, self._solution)

    async def get_page_async(self, target_url: str) -> UserPage:
        """
        Asynchronously retrieve a specific page of UserInstance records from the API.
        Request is executed immediately

        :param target_url: API-generated URL for the requested results page

        :returns: Page of UserInstance
        """
        response = await self._version.domain.twilio.request_async("GET", target_url)
        return UserPage(self._version, response, self._solution)

    def get(self, id: str) -> UserContext:
        """
        Constructs a UserContext

        :param id:
        """
        return UserContext(
            self._version, organization_sid=self._solution["organization_sid"], id=id
        )

    def __call__(self, id: str) -> UserContext:
        """
        Constructs a UserContext

        :param id:
        """
        return UserContext(
            self._version, organization_sid=self._solution["organization_sid"], id=id
        )

    def __repr__(self) -> str:
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        """
        return "<Twilio.PreviewIam.Versionless.UserList>"
