# coding: utf-8

"""
    ETAPI

    External Trilium API

    The version of the OpenAPI document: 1.0.0
    Contact: zadam.apps@gmail.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 pydantic import (
    BaseModel,
    ConfigDict,
    Field,
    StrictBool,
    StrictStr,
    field_validator,
)
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from trilium_client.models.attribute import Attribute
from typing import Optional, Set
from typing_extensions import Self


class Note(BaseModel):
    """
    Note
    """  # noqa: E501

    note_id: Optional[Annotated[str, Field(strict=True)]] = Field(
        default=None, alias="noteId"
    )
    title: Optional[StrictStr] = None
    type: Optional[StrictStr] = None
    mime: Optional[StrictStr] = None
    is_protected: Optional[StrictBool] = Field(default=None, alias="isProtected")
    blob_id: Optional[StrictStr] = Field(
        default=None,
        description="ID of the blob object which effectively serves as a content hash",
        alias="blobId",
    )
    attributes: Optional[List[Attribute]] = None
    parent_note_ids: Optional[List[Annotated[str, Field(strict=True)]]] = Field(
        default=None, alias="parentNoteIds"
    )
    child_note_ids: Optional[List[Annotated[str, Field(strict=True)]]] = Field(
        default=None, alias="childNoteIds"
    )
    parent_branch_ids: Optional[List[Annotated[str, Field(strict=True)]]] = Field(
        default=None, alias="parentBranchIds"
    )
    child_branch_ids: Optional[List[Annotated[str, Field(strict=True)]]] = Field(
        default=None, alias="childBranchIds"
    )
    date_created: Optional[Annotated[str, Field(strict=True)]] = Field(
        default=None, alias="dateCreated"
    )
    date_modified: Optional[Annotated[str, Field(strict=True)]] = Field(
        default=None, alias="dateModified"
    )
    utc_date_created: Optional[Annotated[str, Field(strict=True)]] = Field(
        default=None, alias="utcDateCreated"
    )
    utc_date_modified: Optional[Annotated[str, Field(strict=True)]] = Field(
        default=None, alias="utcDateModified"
    )
    __properties: ClassVar[List[str]] = [
        "noteId",
        "title",
        "type",
        "mime",
        "isProtected",
        "blobId",
        "attributes",
        "parentNoteIds",
        "childNoteIds",
        "parentBranchIds",
        "childBranchIds",
        "dateCreated",
        "dateModified",
        "utcDateCreated",
        "utcDateModified",
    ]

    @field_validator("note_id")
    def note_id_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(r"[a-zA-Z0-9_]{4,32}", value):
            raise ValueError(
                r"must validate the regular expression /[a-zA-Z0-9_]{4,32}/"
            )
        return value

    @field_validator("type")
    def type_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(
            [
                "text",
                "code",
                "render",
                "file",
                "image",
                "search",
                "relationMap",
                "book",
                "noteMap",
                "mermaid",
                "webView",
                "shortcut",
                "doc",
                "contentWidget",
                "launcher",
            ]
        ):
            raise ValueError(
                "must be one of enum values ('text', 'code', 'render', 'file', 'image', 'search', 'relationMap', 'book', 'noteMap', 'mermaid', 'webView', 'shortcut', 'doc', 'contentWidget', 'launcher')"
            )
        return value

    @field_validator("date_created")
    def date_created_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(
            r"[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}[\+\-][0-9]{4}",
            value,
        ):
            raise ValueError(
                r"must validate the regular expression /[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}[\+\-][0-9]{4}/"
            )
        return value

    @field_validator("date_modified")
    def date_modified_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(
            r"[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}[\+\-][0-9]{4}",
            value,
        ):
            raise ValueError(
                r"must validate the regular expression /[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}[\+\-][0-9]{4}/"
            )
        return value

    @field_validator("utc_date_created")
    def utc_date_created_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(
            r"[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z", value
        ):
            raise ValueError(
                r"must validate the regular expression /[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z/"
            )
        return value

    @field_validator("utc_date_modified")
    def utc_date_modified_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(
            r"[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z", value
        ):
            raise ValueError(
                r"must validate the regular expression /[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z/"
            )
        return value

    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 Note 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.
        """
        excluded_fields: Set[str] = set(
            [
                "is_protected",
            ]
        )

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of each item in attributes (list)
        _items = []
        if self.attributes:
            for _item_attributes in self.attributes:
                if _item_attributes:
                    _items.append(_item_attributes.to_dict())
            _dict["attributes"] = _items
        return _dict

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

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

        _obj = cls.model_validate(
            {
                "noteId": obj.get("noteId"),
                "title": obj.get("title"),
                "type": obj.get("type"),
                "mime": obj.get("mime"),
                "isProtected": obj.get("isProtected"),
                "blobId": obj.get("blobId"),
                "attributes": [
                    Attribute.from_dict(_item) for _item in obj["attributes"]
                ]
                if obj.get("attributes") is not None
                else None,
                "parentNoteIds": obj.get("parentNoteIds"),
                "childNoteIds": obj.get("childNoteIds"),
                "parentBranchIds": obj.get("parentBranchIds"),
                "childBranchIds": obj.get("childBranchIds"),
                "dateCreated": obj.get("dateCreated"),
                "dateModified": obj.get("dateModified"),
                "utcDateCreated": obj.get("utcDateCreated"),
                "utcDateModified": obj.get("utcDateModified"),
            }
        )
        return _obj
