# coding: utf-8

"""
    BoldSign API

    No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)

    The version of the OpenAPI document: 1
    Contact: support@boldsign.com
    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, StrictBool, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from boldsign.models.document_cc_webhook_model import DocumentCcWebhookModel
from boldsign.models.document_sender import DocumentSender
from boldsign.models.document_signer_webhook_model import DocumentSignerWebhookModel
from typing import Optional, Set, Tuple
from typing_extensions import Self
import io
from pydantic import StrictBool
from typing import Union

class DocumentEvent(BaseModel):
    """
    DocumentEvent
    """ # noqa: E501
    object: Optional[StrictStr] = None
    document_id: Optional[StrictStr] = Field(default=None, alias="documentId")
    message_title: Optional[StrictStr] = Field(default=None, alias="messageTitle")
    document_description: Optional[StrictStr] = Field(default=None, alias="documentDescription")
    status: Optional[StrictStr] = None
    sender_detail: Optional[DocumentSender] = Field(default=None, alias="senderDetail")
    signer_details: Optional[List[DocumentSignerWebhookModel]] = Field(default=None, alias="signerDetails")
    cc_details: Optional[List[DocumentCcWebhookModel]] = Field(default=None, alias="ccDetails")
    on_behalf_of: Optional[StrictStr] = Field(default=None, alias="onBehalfOf")
    created_date: Optional[datetime] = Field(default=None, alias="createdDate")
    expiry_date: Optional[datetime] = Field(default=None, alias="expiryDate")
    enable_signing_order: Optional[StrictBool] = Field(default=None, alias="enableSigningOrder")
    disable_emails: Optional[StrictBool] = Field(default=None, alias="disableEmails")
    revoke_message: Optional[StrictStr] = Field(default=None, alias="revokeMessage")
    error_message: Optional[StrictStr] = Field(default=None, alias="errorMessage")
    labels: Optional[List[StrictStr]] = None
    is_combined_audit: Optional[StrictBool] = Field(default=None, alias="isCombinedAudit")
    is_combined_attachment: Optional[StrictBool] = Field(default=None, alias="isCombinedAttachment")
    brand_id: Optional[StrictStr] = Field(default=None, alias="brandId")
    document_download_option: Optional[StrictStr] = Field(default=None, alias="documentDownloadOption")
    meta_data: Optional[Dict[str, Optional[StrictStr]]] = Field(default=None, alias="metaData")
    failed_delivery_mode: Optional[StrictStr] = Field(default=None, alias="failedDeliveryMode")
    __properties: ClassVar[List[str]] = ["object", "documentId", "messageTitle", "documentDescription", "status", "senderDetail", "signerDetails", "ccDetails", "onBehalfOf", "createdDate", "expiryDate", "enableSigningOrder", "disableEmails", "revokeMessage", "errorMessage", "labels", "isCombinedAudit", "isCombinedAttachment", "brandId", "documentDownloadOption", "metaData", "failedDeliveryMode"]

    @field_validator('status')
    def status_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(['InProgress', 'Completed', 'Declined', 'Expired', 'Revoked', 'Draft', 'Scheduled']):
            raise ValueError("must be one of enum values ('InProgress', 'Completed', 'Declined', 'Expired', 'Revoked', 'Draft', 'Scheduled')")
        return value

    @field_validator('failed_delivery_mode')
    def failed_delivery_mode_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(['Email', 'SMS', 'WhatsApp']):
            raise ValueError("must be one of enum values ('Email', 'SMS', 'WhatsApp')")
        return value

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


    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())

    def to_json_form_params(self, excluded_fields: Set[str] = None) -> List[Tuple[str, str]]:
        data: List[Tuple[str, str]] = []

        for key, value in self.to_dict(excluded_fields).items():
            if isinstance(value, (int, str, bool)):
                data.append((key, value))
            elif isinstance(value, list):
                for index, item in enumerate(value):
                    if(isinstance(item, (int, str, bool))):
                        data.append((f'{key}[{index}]', item))
                    elif key == 'files' and isinstance(item, dict):
                        for attribute_name, attribute_value in item.items():
                            full_key = f'{key}[{index}].{attribute_name}'
                            if excluded_fields and full_key in excluded_fields:
                                continue
                            data.append((full_key, attribute_value))
                    else:
                        data.append((key, json.dumps(value[index], ensure_ascii=False)))
            elif isinstance(value, dict):
                for dict_key, dict_value in value.items():
                    if dict_value is not None:
                        data.append((f'{key}[{dict_key}]', str(dict_value)))
            else:
                data.append((key, json.dumps(value, ensure_ascii=False)))

        return data

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

    def to_dict(self, excluded_fields: Set[str] = None) -> 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.
        """

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        return _dict

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

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

        _obj = cls.model_validate({
            "object": obj.get("object"),
            "documentId": obj.get("documentId"),
            "messageTitle": obj.get("messageTitle"),
            "documentDescription": obj.get("documentDescription"),
            "status": obj.get("status"),
            "senderDetail": DocumentSender.from_dict(obj["senderDetail"]) if obj.get("senderDetail") is not None else None,
            "signerDetails": [DocumentSignerWebhookModel.from_dict(_item) for _item in obj["signerDetails"]] if obj.get("signerDetails") is not None else None,
            "ccDetails": [DocumentCcWebhookModel.from_dict(_item) for _item in obj["ccDetails"]] if obj.get("ccDetails") is not None else None,
            "onBehalfOf": obj.get("onBehalfOf"),
            "createdDate": obj.get("createdDate"),
            "expiryDate": obj.get("expiryDate"),
            "enableSigningOrder": obj.get("enableSigningOrder"),
            "disableEmails": obj.get("disableEmails"),
            "revokeMessage": obj.get("revokeMessage"),
            "errorMessage": obj.get("errorMessage"),
            "labels": obj.get("labels"),
            "isCombinedAudit": obj.get("isCombinedAudit"),
            "isCombinedAttachment": obj.get("isCombinedAttachment"),
            "brandId": obj.get("brandId"),
            "documentDownloadOption": obj.get("documentDownloadOption"),
            "metaData": obj.get("metaData"),
            "failedDeliveryMode": obj.get("failedDeliveryMode")
        })
        return _obj

    @classmethod
    def init(cls, data: Any) -> Self:
        """
        Attempt to instantiate and hydrate a new instance of this class
        """
        if isinstance(data, str):
            data = json.loads(data)

        return cls.from_dict(data)

    @classmethod
    def openapi_types(cls) -> Dict[str, str]:
        return {
            "object": "(str,)",
            "document_id": "(str,)",
            "message_title": "(str,)",
            "document_description": "(str,)",
            "status": "(str,)",
            "sender_detail": "(DocumentSender,)",
            "signer_details": "(List[DocumentSignerWebhookModel],)",
            "cc_details": "(List[DocumentCcWebhookModel],)",
            "on_behalf_of": "(str,)",
            "created_date": "(datetime,)",
            "expiry_date": "(datetime,)",
            "enable_signing_order": "(bool,)",
            "disable_emails": "(bool,)",
            "revoke_message": "(str,)",
            "error_message": "(str,)",
            "labels": "(List[str],)",
            "is_combined_audit": "(bool,)",
            "is_combined_attachment": "(bool,)",
            "brand_id": "(str,)",
            "document_download_option": "(str,)",
            "meta_data": "(Dict[str, Optional[str]],)",
            "failed_delivery_mode": "(str,)",
        }

    @classmethod
    def openapi_type_is_array(cls, property_name: str) -> bool:
        return property_name in [
            "signer_details",
            "cc_details",
            "labels",
        ]

