# coding: utf-8

"""
    ICAT+ API

    ICAT+ RESTful API with Swagger

    The version of the OpenAPI document: 1.0.0
    Contact: demariaa@esrf.fr
    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 date
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from icat_plus_client.models.event_content_inner import EventContentInner
from icat_plus_client.models.ewoks_session_id_jobs_post_request import EwoksSessionIdJobsPostRequest
from typing import Optional, Set
from typing_extensions import Self

class Event(BaseModel):
    """
    an event in the logbook
    """ # noqa: E501
    id: Optional[StrictInt] = Field(default=None, alias="_id")
    investigation_id: StrictInt = Field(alias="investigationId")
    investigation_name: Optional[StrictStr] = Field(default=None, alias="investigationName")
    instrument_name: Optional[StrictStr] = Field(default=None, alias="instrumentName")
    dataset_id: Optional[StrictInt] = Field(default=None, alias="datasetId")
    type: StrictStr = Field(description="Type of the event")
    tag: Optional[List[EwoksSessionIdJobsPostRequest]] = None
    title: Optional[StrictStr] = None
    category: StrictStr = Field(description="Category of the event")
    filepath: Optional[StrictStr] = None
    filename: Optional[StrictStr] = None
    file_size: Optional[StrictStr] = Field(default=None, alias="fileSize")
    username: Optional[StrictStr] = None
    content: Optional[List[EventContentInner]] = None
    software: Optional[StrictStr] = None
    machine: Optional[StrictStr] = None
    source: Optional[StrictStr] = None
    creation_date: Optional[date] = Field(default=None, alias="creationDate")
    content_type: Optional[StrictStr] = Field(default=None, alias="contentType")
    file: Optional[StrictStr] = None
    previous_version_event: Optional[Dict[str, Any]] = Field(default=None, alias="previousVersionEvent")
    __properties: ClassVar[List[str]] = ["_id", "investigationId", "investigationName", "instrumentName", "datasetId", "type", "tag", "title", "category", "filepath", "filename", "fileSize", "username", "content", "software", "machine", "source", "creationDate", "contentType", "file", "previousVersionEvent"]

    @field_validator('type')
    def type_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['notification', 'annotation', 'broadcast']):
            raise ValueError("must be one of enum values ('notification', 'annotation', 'broadcast')")
        return value

    @field_validator('category')
    def category_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['commandline', 'comment', 'error', 'debug', 'info']):
            raise ValueError("must be one of enum values ('commandline', 'comment', 'error', 'debug', 'info')")
        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 Event 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 each item in tag (list)
        _items = []
        if self.tag:
            for _item_tag in self.tag:
                if _item_tag:
                    _items.append(_item_tag.to_dict())
            _dict['tag'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in content (list)
        _items = []
        if self.content:
            for _item_content in self.content:
                if _item_content:
                    _items.append(_item_content.to_dict())
            _dict['content'] = _items
        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of Event 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"),
            "investigationId": obj.get("investigationId"),
            "investigationName": obj.get("investigationName"),
            "instrumentName": obj.get("instrumentName"),
            "datasetId": obj.get("datasetId"),
            "type": obj.get("type"),
            "tag": [EwoksSessionIdJobsPostRequest.from_dict(_item) for _item in obj["tag"]] if obj.get("tag") is not None else None,
            "title": obj.get("title"),
            "category": obj.get("category"),
            "filepath": obj.get("filepath"),
            "filename": obj.get("filename"),
            "fileSize": obj.get("fileSize"),
            "username": obj.get("username"),
            "content": [EventContentInner.from_dict(_item) for _item in obj["content"]] if obj.get("content") is not None else None,
            "software": obj.get("software"),
            "machine": obj.get("machine"),
            "source": obj.get("source"),
            "creationDate": obj.get("creationDate"),
            "contentType": obj.get("contentType"),
            "file": obj.get("file"),
            "previousVersionEvent": obj.get("previousVersionEvent")
        })
        return _obj


