# coding: utf-8

"""
    ibl-data-manager

    API for iblai

    The version of the OpenAPI document: 4.202.1-ai-plus
    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 datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from iblai.models.external_service_info import ExternalServiceInfo
from typing import Optional, Set
from typing_extensions import Self

class ConnectedService(BaseModel):
    """
    Serializer for representing connected OAuth services.  Includes both the legacy `service` / `scope` string values and structured representations so that consumers can reason about individual scope names.
    """ # noqa: E501
    id: StrictInt
    provider: Annotated[str, Field(strict=True, max_length=128)]
    service: Optional[Annotated[str, Field(strict=True, max_length=255)]] = None
    expires_at: Optional[datetime] = None
    scope: Optional[StrictStr] = None
    scope_names: List[StrictStr] = Field(description="Return the canonical list of scope identifiers for the connection.")
    scopes: List[StrictStr] = Field(description="Return the OAuth scope strings associated with the connection.")
    token_type: Optional[Annotated[str, Field(strict=True, max_length=32)]] = None
    service_info: ExternalServiceInfo
    username: List[StrictStr] = Field(description="Return the username strings associated with the connection.")
    __properties: ClassVar[List[str]] = ["id", "provider", "service", "expires_at", "scope", "scope_names", "scopes", "token_type", "service_info", "username"]

    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 ConnectedService 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.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        """
        excluded_fields: Set[str] = set([
            "id",
            "scope_names",
            "scopes",
            "service_info",
            "username",
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of service_info
        if self.service_info:
            _dict['service_info'] = self.service_info.to_dict()
        # set to None if expires_at (nullable) is None
        # and model_fields_set contains the field
        if self.expires_at is None and "expires_at" in self.model_fields_set:
            _dict['expires_at'] = None

        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of ConnectedService 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"),
            "provider": obj.get("provider"),
            "service": obj.get("service"),
            "expires_at": obj.get("expires_at"),
            "scope": obj.get("scope"),
            "scope_names": obj.get("scope_names"),
            "scopes": obj.get("scopes"),
            "token_type": obj.get("token_type"),
            "service_info": ExternalServiceInfo.from_dict(obj["service_info"]) if obj.get("service_info") is not None else None,
            "username": obj.get("username")
        })
        return _obj


