# coding: utf-8

"""
    Eazyrent IAM API

    EazyRent IAM API ==================  Description -------------  The EazyRent IAM API provides robust identity and access management capabilities, enabling efficient account management and permission controls across the platform. Tailored for the SaaS environment, this API allows administrators to handle user authentication, manage roles, and define permissions to secure access to various resources. By centralizing user accounts and access rules, the IAM API ensures a secure, organized, and scalable approach to managing tenant and staff permissions.  Target Audience ------------------   * **Real Estate Agencies and Social Housing Providers:** Organizations requiring a secure, structured way to manage access for staff and tenants, ensuring that only authorized users can access specific resources and functionalities.   * **Rent Guarantee Insurers:** Companies that need to manage and restrict access to sensitive information, allowing only certain roles to handle tenant verification and risk assessment data.  Purpose --------  The purpose of the EazyRent IAM API is to centralize identity and permission management for platform users. Through this API, businesses can handle account creation, manage user roles, assign permissions, and track access to critical resources, all while ensuring compliance and data security. This results in streamlined operations, allowing clients to configure role-based access in alignment with organizational policies and requirements.  How to use this API -----------------------  To start using the EazyRent IAM API, consult our detailed documentation, which provides information on authentication, endpoint definitions, and integration best practices. This documentation covers the steps required to manage user identities, roles, and permissions within your existing systems, ensuring secure and efficient access control across the platform.

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

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


from __future__ import annotations
import json
import pprint
from pydantic import (
    BaseModel,
    ConfigDict,
    Field,
    StrictStr,
    ValidationError,
    field_validator,
)
from typing import Any, List, Optional
from eazyrent.iam.v1.models.service_account import ServiceAccount
from eazyrent.iam.v1.models.user import User
from pydantic import StrictStr, Field
from typing import Union, List, Set, Optional, Dict
from typing_extensions import Literal, Self

RESPONSEGETMYUSER_ONE_OF_SCHEMAS = ["ServiceAccount", "User"]


class ResponseGetMyUser(BaseModel):
    """
    ResponseGetMyUser
    """

    # data type: User
    oneof_schema_1_validator: Optional[User] = None
    # data type: ServiceAccount
    oneof_schema_2_validator: Optional[ServiceAccount] = None
    actual_instance: Optional[Union[ServiceAccount, User]] = None
    one_of_schemas: Set[str] = {"ServiceAccount", "User"}

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

    discriminator_value_class_map: Dict[str, str] = {}

    def __init__(self, *args, **kwargs) -> None:
        if args:
            if len(args) > 1:
                raise ValueError(
                    "If a position argument is used, only 1 is allowed to set `actual_instance`"
                )
            if kwargs:
                raise ValueError(
                    "If a position argument is used, keyword arguments cannot be used."
                )
            super().__init__(actual_instance=args[0])
        else:
            super().__init__(**kwargs)

    @field_validator("actual_instance")
    def actual_instance_must_validate_oneof(cls, v):
        instance = ResponseGetMyUser.model_construct()
        error_messages = []
        match = 0
        # validate data type: User
        if not isinstance(v, User):
            error_messages.append(f"Error! Input type `{type(v)}` is not `User`")
        else:
            match += 1
        # validate data type: ServiceAccount
        if not isinstance(v, ServiceAccount):
            error_messages.append(
                f"Error! Input type `{type(v)}` is not `ServiceAccount`"
            )
        else:
            match += 1
        if match > 1:
            # more than 1 match
            raise ValueError(
                "Multiple matches found when setting `actual_instance` in ResponseGetMyUser with oneOf schemas: ServiceAccount, User. Details: "
                + ", ".join(error_messages)
            )
        elif match == 0:
            # no match
            raise ValueError(
                "No match found when setting `actual_instance` in ResponseGetMyUser with oneOf schemas: ServiceAccount, User. Details: "
                + ", ".join(error_messages)
            )
        else:
            return v

    @classmethod
    def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self:
        return cls.from_json(json.dumps(obj))

    @classmethod
    def from_json(cls, json_str: str) -> Self:
        """Returns the object represented by the json string"""
        instance = cls.model_construct()
        error_messages = []
        match = 0

        # use oneOf discriminator to lookup the data type
        _data_type = json.loads(json_str).get("user_type")
        if not _data_type:
            raise ValueError(
                "Failed to lookup data type from the field `user_type` in the input."
            )

        # check if data type is `User`
        if _data_type == "Human":
            instance.actual_instance = User.from_json(json_str)
            return instance

        # check if data type is `ServiceAccount`
        if _data_type == "Machine":
            instance.actual_instance = ServiceAccount.from_json(json_str)
            return instance

        # check if data type is `ServiceAccount`
        if _data_type == "ServiceAccount":
            instance.actual_instance = ServiceAccount.from_json(json_str)
            return instance

        # check if data type is `User`
        if _data_type == "User":
            instance.actual_instance = User.from_json(json_str)
            return instance

        # deserialize data into User
        try:
            instance.actual_instance = User.from_json(json_str)
            match += 1
        except (ValidationError, ValueError) as e:
            error_messages.append(str(e))
        # deserialize data into ServiceAccount
        try:
            instance.actual_instance = ServiceAccount.from_json(json_str)
            match += 1
        except (ValidationError, ValueError) as e:
            error_messages.append(str(e))

        if match > 1:
            # more than 1 match
            raise ValueError(
                "Multiple matches found when deserializing the JSON string into ResponseGetMyUser with oneOf schemas: ServiceAccount, User. Details: "
                + ", ".join(error_messages)
            )
        elif match == 0:
            # no match
            raise ValueError(
                "No match found when deserializing the JSON string into ResponseGetMyUser with oneOf schemas: ServiceAccount, User. Details: "
                + ", ".join(error_messages)
            )
        else:
            return instance

    def to_json(self) -> str:
        """Returns the JSON representation of the actual instance"""
        if self.actual_instance is None:
            return "null"

        if hasattr(self.actual_instance, "to_json") and callable(
            self.actual_instance.to_json
        ):
            return self.actual_instance.to_json()
        else:
            return json.dumps(self.actual_instance)

    def to_dict(self) -> Optional[Union[Dict[str, Any], ServiceAccount, User]]:
        """Returns the dict representation of the actual instance"""
        if self.actual_instance is None:
            return None

        if hasattr(self.actual_instance, "to_dict") and callable(
            self.actual_instance.to_dict
        ):
            return self.actual_instance.to_dict()
        else:
            # primitive type
            return self.actual_instance

    def to_str(self) -> str:
        """Returns the string representation of the actual instance"""
        return pprint.pformat(self.model_dump())
