# coding: utf-8

"""
    Teambition Open API

    Teambition Open API

    The version of the OpenAPI document: 1.0.0
    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, StrictFloat, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional, Union
from teambition_oapi_sdk.model.sync_builds_request_build_cause import SyncBuildsRequestBuildCause
from teambition_oapi_sdk.model.sync_builds_request_build_change_sets_inner import SyncBuildsRequestBuildChangeSetsInner
from teambition_oapi_sdk.model.sync_builds_request_build_repo import SyncBuildsRequestBuildRepo
from teambition_oapi_sdk.model.sync_builds_request_build_stages_inner import SyncBuildsRequestBuildStagesInner
from typing import Optional, Set
from typing_extensions import Self

class SyncBuildsRequestBuild(BaseModel):
    """
    构建信息
    """ # noqa: E501
    code: Optional[StrictStr] = Field(default=None, description="构建code，在流水线内唯一，为空时默认使用number")
    number: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="构建序号")
    status: Optional[StrictStr] = Field(default=None, description="构建状态，目前支持运行中(running)、通过(passed)、不稳定(unstable)、中止(aborted)、失败(failed)、未知状态(unKnown)")
    duration: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="构建时长，单位毫秒")
    timestamp: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="构建开始的时间戳")
    url: Optional[StrictStr] = Field(default=None, description="构建地址")
    log: Optional[StrictStr] = Field(default=None, description="构建日志")
    cause: Optional[SyncBuildsRequestBuildCause] = None
    repo: Optional[SyncBuildsRequestBuildRepo] = None
    change_sets: Optional[List[SyncBuildsRequestBuildChangeSetsInner]] = Field(default=None, description="变更信息", alias="changeSets")
    stages: Optional[List[SyncBuildsRequestBuildStagesInner]] = Field(default=None, description="阶段信息（流水线类型必填）")
    __properties: ClassVar[List[str]] = ["code", "number", "status", "duration", "timestamp", "url", "log", "cause", "repo", "changeSets", "stages"]

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

        if value not in set(['BuildStatusList']):
            raise ValueError("must be one of enum values ('BuildStatusList')")
        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 SyncBuildsRequestBuild 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 cause
        if self.cause:
            _dict['cause'] = self.cause.to_dict()
        # override the default output from pydantic by calling `to_dict()` of repo
        if self.repo:
            _dict['repo'] = self.repo.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in change_sets (list)
        _items = []
        if self.change_sets:
            for _item_change_sets in self.change_sets:
                if _item_change_sets:
                    _items.append(_item_change_sets.to_dict())
            _dict['changeSets'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in stages (list)
        _items = []
        if self.stages:
            for _item_stages in self.stages:
                if _item_stages:
                    _items.append(_item_stages.to_dict())
            _dict['stages'] = _items
        return _dict

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

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

        _obj = cls.model_validate({
            "code": obj.get("code"),
            "number": obj.get("number"),
            "status": obj.get("status"),
            "duration": obj.get("duration"),
            "timestamp": obj.get("timestamp"),
            "url": obj.get("url"),
            "log": obj.get("log"),
            "cause": SyncBuildsRequestBuildCause.from_dict(obj["cause"]) if obj.get("cause") is not None else None,
            "repo": SyncBuildsRequestBuildRepo.from_dict(obj["repo"]) if obj.get("repo") is not None else None,
            "changeSets": [SyncBuildsRequestBuildChangeSetsInner.from_dict(_item) for _item in obj["changeSets"]] if obj.get("changeSets") is not None else None,
            "stages": [SyncBuildsRequestBuildStagesInner.from_dict(_item) for _item in obj["stages"]] if obj.get("stages") is not None else None
        })
        return _obj


