# Copyright 2025 21X AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import datetime
from collections.abc import Mapping
from typing import Any, TypeVar, Union

from attrs import define as _attrs_define
from attrs import field as _attrs_field
from dateutil.parser import isoparse

from ..models.finality_status_enum import FinalityStatusEnum
from ..models.order_execution_condition_enum import OrderExecutionConditionEnum
from ..models.order_kind_enum import OrderKindEnum
from ..models.order_status_enum import OrderStatusEnum
from ..models.order_status_reason_enum import OrderStatusReasonEnum
from ..models.order_type_enum import OrderTypeEnum
from ..types import UNSET, Unset

T = TypeVar("T", bound="Order")


@_attrs_define
class Order:
    """
    Attributes:
        id (str):
        trading_pair_id (str): The trading pair that the order belongs to
        order_kind (OrderKindEnum):
        order_type (OrderTypeEnum):
        initial_quantity (str): Initial order size in financial instrument (base) tokens (as sent to the order book)
        remaining_quantity (str): Remaining order size in financial instrument (base) tokens (can be lower than the
            initial quantity in case of partial executions)
        address (str): The address of the wallet that the order was sent from
        creation_date (Union[Unset, datetime.datetime]):
        modification_date (Union[Unset, datetime.datetime]):
        external_order_id (Union[Unset, int]): ID generated by the order book smart contract
        price_limit (Union[Unset, str]): The price limit is mandatory for limit orders
        status (Union[Unset, OrderStatusEnum]):
        status_reason (Union[Unset, OrderStatusReasonEnum]):
        status_change_time (Union[Unset, datetime.datetime]): The date and time when the order was fully executed,
            rejected or cancelled
        finality_status (Union[Unset, FinalityStatusEnum]):
        owner_reporting_data (Union[Unset, str]): The bit string that the creator passed as reportingData to the smart
            contract, encoded as a hexadecimal string
        cross_identifier (Union[Unset, int]): 32-bit integer that can be used to distinguish between participants using
            the same wallet, disabling self-trade checks between different cross-IDs.
        valid_until (Union[Unset, datetime.datetime]): The latest date at which the order is automatically cancelled
        execution_condition (Union[Unset, OrderExecutionConditionEnum]):
    """

    id: str
    trading_pair_id: str
    order_kind: OrderKindEnum
    order_type: OrderTypeEnum
    initial_quantity: str
    remaining_quantity: str
    address: str
    creation_date: Union[Unset, datetime.datetime] = UNSET
    modification_date: Union[Unset, datetime.datetime] = UNSET
    external_order_id: Union[Unset, int] = UNSET
    price_limit: Union[Unset, str] = UNSET
    status: Union[Unset, OrderStatusEnum] = UNSET
    status_reason: Union[Unset, OrderStatusReasonEnum] = UNSET
    status_change_time: Union[Unset, datetime.datetime] = UNSET
    finality_status: Union[Unset, FinalityStatusEnum] = UNSET
    owner_reporting_data: Union[Unset, str] = UNSET
    cross_identifier: Union[Unset, int] = UNSET
    valid_until: Union[Unset, datetime.datetime] = UNSET
    execution_condition: Union[Unset, OrderExecutionConditionEnum] = UNSET
    additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)

    def to_dict(self) -> dict[str, Any]:
        id = self.id

        trading_pair_id = self.trading_pair_id

        order_kind = self.order_kind.value

        order_type = self.order_type.value

        initial_quantity = self.initial_quantity

        remaining_quantity = self.remaining_quantity

        address = self.address

        creation_date: Union[Unset, str] = UNSET
        if not isinstance(self.creation_date, Unset):
            creation_date = self.creation_date.isoformat()

        modification_date: Union[Unset, str] = UNSET
        if not isinstance(self.modification_date, Unset):
            modification_date = self.modification_date.isoformat()

        external_order_id = self.external_order_id

        price_limit = self.price_limit

        status: Union[Unset, str] = UNSET
        if not isinstance(self.status, Unset):
            status = self.status.value

        status_reason: Union[Unset, str] = UNSET
        if not isinstance(self.status_reason, Unset):
            status_reason = self.status_reason.value

        status_change_time: Union[Unset, str] = UNSET
        if not isinstance(self.status_change_time, Unset):
            status_change_time = self.status_change_time.isoformat()

        finality_status: Union[Unset, str] = UNSET
        if not isinstance(self.finality_status, Unset):
            finality_status = self.finality_status.value

        owner_reporting_data = self.owner_reporting_data

        cross_identifier = self.cross_identifier

        valid_until: Union[Unset, str] = UNSET
        if not isinstance(self.valid_until, Unset):
            valid_until = self.valid_until.isoformat()

        execution_condition: Union[Unset, str] = UNSET
        if not isinstance(self.execution_condition, Unset):
            execution_condition = self.execution_condition.value

        field_dict: dict[str, Any] = {}
        field_dict.update(self.additional_properties)
        field_dict.update(
            {
                "id": id,
                "tradingPairId": trading_pair_id,
                "orderKind": order_kind,
                "orderType": order_type,
                "initialQuantity": initial_quantity,
                "remainingQuantity": remaining_quantity,
                "address": address,
            }
        )
        if creation_date is not UNSET:
            field_dict["creationDate"] = creation_date
        if modification_date is not UNSET:
            field_dict["modificationDate"] = modification_date
        if external_order_id is not UNSET:
            field_dict["externalOrderId"] = external_order_id
        if price_limit is not UNSET:
            field_dict["priceLimit"] = price_limit
        if status is not UNSET:
            field_dict["status"] = status
        if status_reason is not UNSET:
            field_dict["statusReason"] = status_reason
        if status_change_time is not UNSET:
            field_dict["statusChangeTime"] = status_change_time
        if finality_status is not UNSET:
            field_dict["finalityStatus"] = finality_status
        if owner_reporting_data is not UNSET:
            field_dict["ownerReportingData"] = owner_reporting_data
        if cross_identifier is not UNSET:
            field_dict["crossIdentifier"] = cross_identifier
        if valid_until is not UNSET:
            field_dict["validUntil"] = valid_until
        if execution_condition is not UNSET:
            field_dict["executionCondition"] = execution_condition

        return field_dict

    @classmethod
    def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
        d = dict(src_dict)
        id = d.pop("id")

        trading_pair_id = d.pop("tradingPairId")

        order_kind = OrderKindEnum(d.pop("orderKind"))

        order_type = OrderTypeEnum(d.pop("orderType"))

        initial_quantity = d.pop("initialQuantity")

        remaining_quantity = d.pop("remainingQuantity")

        address = d.pop("address")

        _creation_date = d.pop("creationDate", UNSET)
        creation_date: Union[Unset, datetime.datetime]
        if isinstance(_creation_date, Unset):
            creation_date = UNSET
        else:
            creation_date = isoparse(_creation_date)

        _modification_date = d.pop("modificationDate", UNSET)
        modification_date: Union[Unset, datetime.datetime]
        if isinstance(_modification_date, Unset):
            modification_date = UNSET
        else:
            modification_date = isoparse(_modification_date)

        external_order_id = d.pop("externalOrderId", UNSET)

        price_limit = d.pop("priceLimit", UNSET)

        _status = d.pop("status", UNSET)
        status: Union[Unset, OrderStatusEnum]
        if isinstance(_status, Unset):
            status = UNSET
        else:
            status = OrderStatusEnum(_status)

        _status_reason = d.pop("statusReason", UNSET)
        status_reason: Union[Unset, OrderStatusReasonEnum]
        if isinstance(_status_reason, Unset):
            status_reason = UNSET
        else:
            status_reason = OrderStatusReasonEnum(_status_reason)

        _status_change_time = d.pop("statusChangeTime", UNSET)
        status_change_time: Union[Unset, datetime.datetime]
        if isinstance(_status_change_time, Unset):
            status_change_time = UNSET
        else:
            status_change_time = isoparse(_status_change_time)

        _finality_status = d.pop("finalityStatus", UNSET)
        finality_status: Union[Unset, FinalityStatusEnum]
        if isinstance(_finality_status, Unset):
            finality_status = UNSET
        else:
            finality_status = FinalityStatusEnum(_finality_status)

        owner_reporting_data = d.pop("ownerReportingData", UNSET)

        cross_identifier = d.pop("crossIdentifier", UNSET)

        _valid_until = d.pop("validUntil", UNSET)
        valid_until: Union[Unset, datetime.datetime]
        if isinstance(_valid_until, Unset):
            valid_until = UNSET
        else:
            valid_until = isoparse(_valid_until)

        _execution_condition = d.pop("executionCondition", UNSET)
        execution_condition: Union[Unset, OrderExecutionConditionEnum]
        if isinstance(_execution_condition, Unset):
            execution_condition = UNSET
        else:
            execution_condition = OrderExecutionConditionEnum(_execution_condition)

        order = cls(
            id=id,
            trading_pair_id=trading_pair_id,
            order_kind=order_kind,
            order_type=order_type,
            initial_quantity=initial_quantity,
            remaining_quantity=remaining_quantity,
            address=address,
            creation_date=creation_date,
            modification_date=modification_date,
            external_order_id=external_order_id,
            price_limit=price_limit,
            status=status,
            status_reason=status_reason,
            status_change_time=status_change_time,
            finality_status=finality_status,
            owner_reporting_data=owner_reporting_data,
            cross_identifier=cross_identifier,
            valid_until=valid_until,
            execution_condition=execution_condition,
        )

        order.additional_properties = d
        return order

    @property
    def additional_keys(self) -> list[str]:
        return list(self.additional_properties.keys())

    def __getitem__(self, key: str) -> Any:
        return self.additional_properties[key]

    def __setitem__(self, key: str, value: Any) -> None:
        self.additional_properties[key] = value

    def __delitem__(self, key: str) -> None:
        del self.additional_properties[key]

    def __contains__(self, key: str) -> bool:
        return key in self.additional_properties
