# coding: utf-8

"""
Kaziro API

Kaziro Trading API Documentation

The version of the OpenAPI document: 1.0.5
Generated by OpenAPI Generator (https://openapi-generator.tech)

Do not edit the class manually.
"""  # noqa: E501

from __future__ import annotations

import json
import pprint
import re  # noqa: F401
from typing import Any, ClassVar, Dict, List, Optional, Set, Union

from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt, StrictStr, field_validator
from typing_extensions import Self

from ..models.market import Market


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

    id: StrictStr = Field(description="Unique identifier for the created order.")
    date_created: StrictStr = Field(description="Timestamp of order creation.")
    market_id: StrictStr = Field(description="Market identifier for the order.")
    wallet_id: Optional[StrictStr] = Field(default=None, description="Wallet identifier associated with the order.")
    status: StrictStr = Field(description="Current status of the order.")
    probability: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="Probability set for the order.")
    size: Union[StrictFloat, StrictInt] = Field(description="Size of the order.")
    order_type: StrictStr = Field(description="Type of the order.")
    expiry_type: StrictStr = Field(description="Expiration type of the order.")
    request_id: Optional[StrictStr] = Field(default=None, description="Request identifier associated with the order.")
    metadata: Optional[Dict[str, Any]] = Field(default=None, description="Metadata associated with the order.")
    market: Optional[Market] = Field(default=None, description="Market associated with the order.")
    __properties: ClassVar[List[str]] = ["id", "date_created", "market_id", "wallet_id", "status", "probability", "size", "order_type", "expiry_type", "request_id", "metadata", "market"]

    @field_validator("status")
    def status_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(["OPEN", "CLOSED", "CANCELLED", "MATCHED"]):
            raise ValueError("must be one of enum values ('OPEN', 'CLOSED', 'CANCELLED', 'MATCHED')")
        return value

    @field_validator("order_type")
    def order_type_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(["MARKET_REQUEST", "MARKET_REPLY"]):
            raise ValueError("must be one of enum values ('MARKET_REQUEST', 'MARKET_REPLY')")
        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 OrderWithMarket 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 market
        if self.market:
            _dict["market"] = self.market.to_dict()
        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of OrderWithMarket 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"),
                "date_created": obj.get("date_created"),
                "market_id": obj.get("market_id"),
                "wallet_id": obj.get("wallet_id"),
                "status": obj.get("status"),
                "probability": obj.get("probability"),
                "size": obj.get("size"),
                "order_type": obj.get("order_type"),
                "expiry_type": obj.get("expiry_type"),
                "request_id": obj.get("request_id"),
                "metadata": obj.get("metadata"),
                "market": Market.from_dict(obj["market"]) if obj.get("market") is not None else None,
            }
        )
        return _obj
