# coding: utf-8

"""
    Gmail API

    The Gmail API lets you view and manage Gmail mailbox data like threads, messages, and labels.

    The version of the OpenAPI document: v1
    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, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from gmail_ti.models.message_part_body import MessagePartBody
from gmail_ti.models.message_part_header import MessagePartHeader
from typing import Optional, Set
from typing_extensions import Self

class MessagePart(BaseModel):
    """
    A single MIME message part.
    """ # noqa: E501
    body: Optional[MessagePartBody] = None
    filename: Optional[StrictStr] = Field(default=None, description="The filename of the attachment. Only present if this message part represents an attachment.")
    headers: Optional[List[MessagePartHeader]] = Field(default=None, description="List of headers on this message part. For the top-level message part, representing the entire message payload, it will contain the standard RFC 2822 email headers such as `To`, `From`, and `Subject`.")
    mime_type: Optional[StrictStr] = Field(default=None, description="The MIME type of the message part.", alias="mimeType")
    part_id: Optional[StrictStr] = Field(default=None, description="The immutable ID of the message part.", alias="partId")
    parts: Optional[List[MessagePart]] = Field(default=None, description="The child MIME message parts of this part. This only applies to container MIME message parts, for example `multipart/*`. For non- container MIME message part types, such as `text/plain`, this field is empty. For more information, see RFC 1521.")
    __properties: ClassVar[List[str]] = ["body", "filename", "headers", "mimeType", "partId", "parts"]

    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 MessagePart 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 body
        if self.body:
            _dict['body'] = self.body.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in headers (list)
        _items = []
        if self.headers:
            for _item_headers in self.headers:
                if _item_headers:
                    _items.append(_item_headers.to_dict())
            _dict['headers'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in parts (list)
        _items = []
        if self.parts:
            for _item_parts in self.parts:
                if _item_parts:
                    _items.append(_item_parts.to_dict())
            _dict['parts'] = _items
        return _dict

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

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

        _obj = cls.model_validate({
            "body": MessagePartBody.from_dict(obj["body"]) if obj.get("body") is not None else None,
            "filename": obj.get("filename"),
            "headers": [MessagePartHeader.from_dict(_item) for _item in obj["headers"]] if obj.get("headers") is not None else None,
            "mimeType": obj.get("mimeType"),
            "partId": obj.get("partId"),
            "parts": [MessagePart.from_dict(_item) for _item in obj["parts"]] if obj.get("parts") is not None else None
        })
        return _obj

# TODO: Rewrite to not use raise_errors
MessagePart.model_rebuild(raise_errors=False)

