# 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, StrictBytes, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, Union
from gmail_ti.models.message_part import MessagePart
from typing import Optional, Set
from typing_extensions import Self

class Message(BaseModel):
    """
    An email message.
    """ # noqa: E501
    history_id: Optional[StrictStr] = Field(default=None, description="The ID of the last history record that modified this message.", alias="historyId")
    id: Optional[StrictStr] = Field(default=None, description="The immutable ID of the message.")
    internal_date: Optional[StrictStr] = Field(default=None, description="The internal message creation timestamp (epoch ms), which determines ordering in the inbox. For normal SMTP-received email, this represents the time the message was originally accepted by Google, which is more reliable than the `Date` header. However, for API-migrated mail, it can be configured by client to be based on the `Date` header.", alias="internalDate")
    label_ids: Optional[List[StrictStr]] = Field(default=None, description="List of IDs of labels applied to this message.", alias="labelIds")
    payload: Optional[MessagePart] = None
    raw: Optional[Union[StrictBytes, StrictStr]] = Field(default=None, description="The entire email message in an RFC 2822 formatted and base64url encoded string. Returned in `messages.get` and `drafts.get` responses when the `format=RAW` parameter is supplied.")
    size_estimate: Optional[StrictInt] = Field(default=None, description="Estimated size in bytes of the message.", alias="sizeEstimate")
    snippet: Optional[StrictStr] = Field(default=None, description="A short part of the message text.")
    thread_id: Optional[StrictStr] = Field(default=None, description="The ID of the thread the message belongs to. To add a message or draft to a thread, the following criteria must be met: 1. The requested `threadId` must be specified on the `Message` or `Draft.Message` you supply with your request. 2. The `References` and `In-Reply-To` headers must be set in compliance with the [RFC 2822](https://tools.ietf.org/html/rfc2822) standard. 3. The `Subject` headers must match. ", alias="threadId")
    __properties: ClassVar[List[str]] = ["historyId", "id", "internalDate", "labelIds", "payload", "raw", "sizeEstimate", "snippet", "threadId"]

    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 Message 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 payload
        if self.payload:
            _dict['payload'] = self.payload.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "historyId": obj.get("historyId"),
            "id": obj.get("id"),
            "internalDate": obj.get("internalDate"),
            "labelIds": obj.get("labelIds"),
            "payload": MessagePart.from_dict(obj["payload"]) if obj.get("payload") is not None else None,
            "raw": obj.get("raw"),
            "sizeEstimate": obj.get("sizeEstimate"),
            "snippet": obj.get("snippet"),
            "threadId": obj.get("threadId")
        })
        return _obj


