# coding: utf-8

"""
Waybiller External API - with fixes

The **Waybiller External API** is a feature that allows companies to access **Waybiller** data as JSON objects and create **Waybiller** instances out of their own data.  To make integration easier for the companies, the external API provides mapping support - it is possible to create company-specific mappings for object identifiers (such as destination and origin).  These mappings will be used for representing companies data from external API, and for converting the values during the creation of **Waybiller** instances (such as transport orders and waybills).  Most of the API responses contain mapped values, which may be null if the company doesn't have a mapping for this object.  Unique **Waybiller** identifiers and values can be accessed via the `raw_data` key.  The API is HTTPS and JSON based.  ### Pagination  By default, list endpoint responses are presented in pages of 30 items.  It is possible to control the page size using the `limit` parameter: `/external-api/<some-list-endpoint>/?limit=<number>`, where `<number>` is an integer between 1 and 1000.

The version of the OpenAPI document: v1
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 datetime import date
from typing import Any, ClassVar, Dict, List, Optional, Set

from pydantic import BaseModel, ConfigDict, Field, field_validator
from typing_extensions import Annotated, Self

from pywaybiller.openapi_client.models.external_api_order_origin import (
    ExternalAPIOrderOrigin,
)
from pywaybiller.openapi_client.models.external_api_order_raw_data import (
    ExternalAPIOrderRawData,
)
from pywaybiller.openapi_client.models.order_status_enum import OrderStatusEnum


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

    order_id: Annotated[str, Field(strict=True, max_length=10)] = Field(
        description="Unique identifier of the order in Waybiller"
    )
    number: Annotated[str, Field(strict=True, max_length=16)] = Field(
        description="Unique order reference number"
    )
    status: OrderStatusEnum = Field(description="Current status of the order")
    period: List[date] = Field(description="Date range when the order is active")
    origins: List[ExternalAPIOrderOrigin] = Field(
        description="List of origins associated with this order"
    )
    owner_company_name: Annotated[str, Field(strict=True, max_length=64)] = Field(
        description="Name of the company that owns this order"
    )
    client_company_name: Annotated[str, Field(strict=True, max_length=64)] = Field(
        description="Name of the client company for whom this order was created"
    )
    destination_name: Annotated[str, Field(strict=True, max_length=255)] = Field(
        description="Name of the destination"
    )
    total_allowed_amount: Optional[Annotated[str, Field(strict=True)]] = Field(
        description="Maximum total quantity allowed for this order"
    )
    raw_data: ExternalAPIOrderRawData = Field(
        description="The IDs of the Waybiller internal objects"
    )
    __properties: ClassVar[List[str]] = [
        "order_id",
        "number",
        "status",
        "period",
        "origins",
        "owner_company_name",
        "client_company_name",
        "destination_name",
        "total_allowed_amount",
        "raw_data",
    ]

    @field_validator("total_allowed_amount")
    def total_allowed_amount_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(r"^-?\d{0,7}(?:\.\d{0,3})?$", value):
            raise ValueError(
                r"must validate the regular expression /^-?\d{0,7}(?:\.\d{0,3})?$/"
            )
        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 ExternalAPIOrderList 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.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        """
        excluded_fields: Set[str] = set(
            [
                "order_id",
                "number",
                "status",
                "period",
                "origins",
                "owner_company_name",
                "client_company_name",
                "destination_name",
                "total_allowed_amount",
                "raw_data",
            ]
        )

        _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 origins (list)
        _items = []
        if self.origins:
            for _item_origins in self.origins:
                if _item_origins:
                    _items.append(_item_origins.to_dict())
            _dict["origins"] = _items
        # override the default output from pydantic by calling `to_dict()` of raw_data
        if self.raw_data:
            _dict["raw_data"] = self.raw_data.to_dict()
        # set to None if total_allowed_amount (nullable) is None
        # and model_fields_set contains the field
        if (
            self.total_allowed_amount is None
            and "total_allowed_amount" in self.model_fields_set
        ):
            _dict["total_allowed_amount"] = None

        return _dict

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

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

        _obj = cls.model_validate(
            {
                "order_id": obj.get("order_id"),
                "number": obj.get("number"),
                "status": obj.get("status"),
                "period": obj.get("period"),
                "origins": [
                    ExternalAPIOrderOrigin.from_dict(_item) for _item in obj["origins"]
                ]
                if obj.get("origins") is not None
                else None,
                "owner_company_name": obj.get("owner_company_name"),
                "client_company_name": obj.get("client_company_name"),
                "destination_name": obj.get("destination_name")
                if obj.get("destination_name") is not None
                else "",
                "total_allowed_amount": obj.get("total_allowed_amount"),
                "raw_data": ExternalAPIOrderRawData.from_dict(obj["raw_data"])
                if obj.get("raw_data") is not None
                else None,
            }
        )
        return _obj
