# coding: utf-8

"""
    Logto API references

    API references for Logto services. To learn more about how to interact with Logto APIs, see [Interact with Management API](https://docs.logto.io/docs/recipes/interact-with-management-api/).

    The version of the OpenAPI document: Cloud
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt
from typing import Any, ClassVar, Dict, List, Union
from typing_extensions import Annotated
from py_logto.models.api_configs_jwt_customizer_token_type_path_get200_response_one_of_context_sample_user_identities_value import ApiConfigsJwtCustomizerTokenTypePathGet200ResponseOneOfContextSampleUserIdentitiesValue
from py_logto.models.api_configs_jwt_customizer_token_type_path_get200_response_one_of_context_sample_user_profile import ApiConfigsJwtCustomizerTokenTypePathGet200ResponseOneOfContextSampleUserProfile
from py_logto.models.api_users_user_id_get200_response_sso_identities_inner import ApiUsersUserIdGet200ResponseSsoIdentitiesInner
from typing import Optional, Set
from typing_extensions import Self


class ApiUsersUserIdGet200Response(BaseModel):
    """
    ApiUsersUserIdGet200Response
    """ # noqa: E501
    id: Annotated[str, Field(min_length=1, strict=True, max_length=12)]
    username: Optional[Annotated[str, Field(strict=True, max_length=128)]]
    primary_email: Optional[Annotated[str, Field(strict=True, max_length=128)]] = Field(alias="primaryEmail")
    primary_phone: Optional[Annotated[str, Field(strict=True, max_length=128)]] = Field(alias="primaryPhone")
    name: Optional[Annotated[str, Field(strict=True, max_length=128)]]
    avatar: Optional[Annotated[str, Field(strict=True, max_length=2048)]]
    custom_data: Dict[str, Any] = Field(description="arbitrary", alias="customData")
    identities: Dict[str, ApiConfigsJwtCustomizerTokenTypePathGet200ResponseOneOfContextSampleUserIdentitiesValue]
    last_sign_in_at: Optional[Union[StrictFloat, StrictInt]] = Field(alias="lastSignInAt")
    created_at: Union[StrictFloat, StrictInt] = Field(alias="createdAt")
    updated_at: Union[StrictFloat, StrictInt] = Field(alias="updatedAt")
    profile: ApiConfigsJwtCustomizerTokenTypePathGet200ResponseOneOfContextSampleUserProfile
    application_id: Optional[Annotated[str, Field(strict=True, max_length=21)]] = Field(alias="applicationId")
    is_suspended: StrictBool = Field(alias="isSuspended")
    has_password: Optional[StrictBool] = Field(default=None, alias="hasPassword")
    sso_identities: Optional[List[ApiUsersUserIdGet200ResponseSsoIdentitiesInner]] = Field(default=None, description="List of SSO identities associated with the user. Only available when the `includeSsoIdentities` query parameter is provided with a truthy value.", alias="ssoIdentities")
    __properties: ClassVar[List[str]] = ["id", "username", "primaryEmail", "primaryPhone", "name", "avatar", "customData", "identities", "lastSignInAt", "createdAt", "updatedAt", "profile", "applicationId", "isSuspended", "hasPassword", "ssoIdentities"]

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.model_dump(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of ApiUsersUserIdGet200Response from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        """
        excluded_fields: Set[str] = set([
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of each value in identities (dict)
        _field_dict = {}
        if self.identities:
            for _key in self.identities:
                if self.identities[_key]:
                    _field_dict[_key] = self.identities[_key].to_dict()
            _dict['identities'] = _field_dict
        # override the default output from pydantic by calling `to_dict()` of profile
        if self.profile:
            _dict['profile'] = self.profile.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in sso_identities (list)
        _items = []
        if self.sso_identities:
            for _item in self.sso_identities:
                if _item:
                    _items.append(_item.to_dict())
            _dict['ssoIdentities'] = _items
        # set to None if username (nullable) is None
        # and model_fields_set contains the field
        if self.username is None and "username" in self.model_fields_set:
            _dict['username'] = None

        # set to None if primary_email (nullable) is None
        # and model_fields_set contains the field
        if self.primary_email is None and "primary_email" in self.model_fields_set:
            _dict['primaryEmail'] = None

        # set to None if primary_phone (nullable) is None
        # and model_fields_set contains the field
        if self.primary_phone is None and "primary_phone" in self.model_fields_set:
            _dict['primaryPhone'] = None

        # set to None if name (nullable) is None
        # and model_fields_set contains the field
        if self.name is None and "name" in self.model_fields_set:
            _dict['name'] = None

        # set to None if avatar (nullable) is None
        # and model_fields_set contains the field
        if self.avatar is None and "avatar" in self.model_fields_set:
            _dict['avatar'] = None

        # set to None if last_sign_in_at (nullable) is None
        # and model_fields_set contains the field
        if self.last_sign_in_at is None and "last_sign_in_at" in self.model_fields_set:
            _dict['lastSignInAt'] = None

        # set to None if application_id (nullable) is None
        # and model_fields_set contains the field
        if self.application_id is None and "application_id" in self.model_fields_set:
            _dict['applicationId'] = None

        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of ApiUsersUserIdGet200Response from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        _obj = cls.model_validate({
            "id": obj.get("id"),
            "username": obj.get("username"),
            "primaryEmail": obj.get("primaryEmail"),
            "primaryPhone": obj.get("primaryPhone"),
            "name": obj.get("name"),
            "avatar": obj.get("avatar"),
            "customData": obj.get("customData"),
            "identities": dict(
                (_k, ApiConfigsJwtCustomizerTokenTypePathGet200ResponseOneOfContextSampleUserIdentitiesValue.from_dict(_v))
                for _k, _v in obj["identities"].items()
            )
            if obj.get("identities") is not None
            else None,
            "lastSignInAt": obj.get("lastSignInAt"),
            "createdAt": obj.get("createdAt"),
            "updatedAt": obj.get("updatedAt"),
            "profile": ApiConfigsJwtCustomizerTokenTypePathGet200ResponseOneOfContextSampleUserProfile.from_dict(obj["profile"]) if obj.get("profile") is not None else None,
            "applicationId": obj.get("applicationId"),
            "isSuspended": obj.get("isSuspended"),
            "hasPassword": obj.get("hasPassword"),
            "ssoIdentities": [ApiUsersUserIdGet200ResponseSsoIdentitiesInner.from_dict(_item) for _item in obj["ssoIdentities"]] if obj.get("ssoIdentities") is not None else None
        })
        return _obj


