# coding: utf-8

"""
    Mender API

    Combined API specification for the features of the different Mender backend services, suitable for code generation applications 

    The version of the OpenAPI document: 1
    Contact: support@mender.io
    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, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from mender_client.models.deployment_phase import DeploymentPhase
from mender_client.models.deployment_statistics import DeploymentStatistics
from mender_client.models.filter_v2 import FilterV2
from typing import Optional, Set
from typing_extensions import Self

class DeploymentV2(BaseModel):
    """
    DeploymentV2
    """ # noqa: E501
    id: StrictStr = Field(description="Deployment identifier")
    name: StrictStr = Field(description="Name of the deployment")
    artifact_name: StrictStr = Field(description="Name of the artifact to deploy")
    created: datetime = Field(description="Deployment's creation date and time")
    finished: Optional[datetime] = Field(default=None, description="Deployment's completion date and time")
    status: StrictStr = Field(description="Status of the deployment")
    device_count: StrictInt = Field(description="Number of devices the deployment acted upon")
    artifacts: Optional[List[StrictStr]] = Field(default=None, description="An array of artifact's identifiers.")
    groups: Optional[List[StrictStr]] = Field(default=None, description="An array of groups the devices targeted by the deployment belong to. Available only if the user created the deployment for a group or a single device (if the device was in a static group). ")
    phases: Optional[List[DeploymentPhase]] = Field(default=None, description="An array of deployments phases (if any were defined for the deployment).")
    retries: Optional[StrictInt] = Field(default=None, description="The number of times a device can retry the deployment in case of failure, defaults to 0")
    update_control_map: Optional[Dict[str, Any]] = Field(default=None, description="A valid JSON object defining the update control map. *NOTE*: Available only in the Enterprise plan. ")
    max_devices: Optional[StrictInt] = Field(default=None, description="max_devices denotes a limit on a number of completed deployments (failed or successful) above which the dynamic deployment will be finished. ")
    initial_device_count: Optional[StrictInt] = Field(default=None, description="In case of dynamic deployments this is a number of devices targeted initially (maching the filter at the moment of deployment creation). ")
    dynamic: Optional[StrictBool] = Field(default=None, description="Flag indicating if the deployment is dynamic or not. ")
    filter: Optional[FilterV2] = None
    type: Optional[StrictStr] = None
    configuration: Optional[StrictStr] = Field(default=None, description="A string containing a configuration object provided with the deployment constructor. ")
    autogenerate_delta: Optional[StrictBool] = Field(default=None, description="The flag idicating if the autogeneration of delta artifacts is enabled for a given deployment. ")
    statistics: Optional[DeploymentStatistics] = None
    __properties: ClassVar[List[str]] = ["id", "name", "artifact_name", "created", "finished", "status", "device_count", "artifacts", "groups", "phases", "retries", "update_control_map", "max_devices", "initial_device_count", "dynamic", "filter", "type", "configuration", "autogenerate_delta", "statistics"]

    @field_validator('status')
    def status_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['scheduled', 'pending', 'inprogress', 'finished']):
            raise ValueError("must be one of enum values ('scheduled', 'pending', 'inprogress', 'finished')")
        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(['configuration', 'software']):
            raise ValueError("must be one of enum values ('configuration', 'software')")
        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 DeploymentV2 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 phases (list)
        _items = []
        if self.phases:
            for _item_phases in self.phases:
                if _item_phases:
                    _items.append(_item_phases.to_dict())
            _dict['phases'] = _items
        # override the default output from pydantic by calling `to_dict()` of filter
        if self.filter:
            _dict['filter'] = self.filter.to_dict()
        # override the default output from pydantic by calling `to_dict()` of statistics
        if self.statistics:
            _dict['statistics'] = self.statistics.to_dict()
        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of DeploymentV2 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"),
            "name": obj.get("name"),
            "artifact_name": obj.get("artifact_name"),
            "created": obj.get("created"),
            "finished": obj.get("finished"),
            "status": obj.get("status"),
            "device_count": obj.get("device_count"),
            "artifacts": obj.get("artifacts"),
            "groups": obj.get("groups"),
            "phases": [DeploymentPhase.from_dict(_item) for _item in obj["phases"]] if obj.get("phases") is not None else None,
            "retries": obj.get("retries"),
            "update_control_map": obj.get("update_control_map"),
            "max_devices": obj.get("max_devices"),
            "initial_device_count": obj.get("initial_device_count"),
            "dynamic": obj.get("dynamic"),
            "filter": FilterV2.from_dict(obj["filter"]) if obj.get("filter") is not None else None,
            "type": obj.get("type"),
            "configuration": obj.get("configuration"),
            "autogenerate_delta": obj.get("autogenerate_delta"),
            "statistics": DeploymentStatistics.from_dict(obj["statistics"]) if obj.get("statistics") is not None else None
        })
        return _obj


