# coding: utf-8

"""
    CATAPA API

    # Introduction CATAPA API uses RESTful API style. It uses JSON data format for data exchange and utilizes HTTP verbs as appropriate.  For authorization & authentication, CATAPA API uses OAuth 2.0 protocol.  # Base URL Production: https://api.catapa.com  # Authentication Clients need to acquire an access token before they send HTTP requests to resource endpoints.  <SecurityDefinitions />  ## Validate Access Token    Use this endpoint to verify if an access token is valid and was issued by the API gateway. The endpoint supports both user tokens and client credentials tokens.    | **HTTP Method**  | `GET`                                                |                                         |   |------------------|------------------------------------------------------|-----------------------------------------|   | **URL**          | `<base-url>/v1/oauth-clients/validate-access-token`  |                                         |   | **Headers**      | `Authorization`                                      | `Bearer <access-token>`                 |   |                  | `Tenant`                                             | Your tenant identifier (e.g., \"catapa\") |  ### Example request using `curl`    ```bash   curl --location '<base-url>/v1/oauth-clients/validate-access-token' \\     --header 'Tenant: catapa' \\     --header 'Authorization: Bearer <access-token>'   ```  ### Response codes  - **200 OK**: Token is valid - **401 Unauthorized**: Token is invalid or expired  ### Notes  - This endpoint validates both user authentication tokens and client credentials tokens - For server-to-server communication, use client credentials flow with the token in the Authorization header - No response body is returned; the status code indicates the validation result - The `Tenant` header is required to specify which tenant context to validate the token against  # HTTP Headers Each request should contain the following headers.  |Headers        |Description  | |---------------|-------------| |Tenant         |Tenant name. e.g. Catapa| |Authorization  |For authentication. Value format: Bearer <access-token>|  Example HTTP Request using cURL: ```bash curl <base-url>/core/v1/employees?page=0&size=10 \\ -H \"Tenant: <tenant name>\" \\ -H \"Authorization: Bearer <access-token>\" ```  # Rate Limit To ensure optimal API performance and fair usage for all users, we implement rate limiting. The general limit is **400 requests per minute, per Client ID**. If you exceed the rate limit, you will receive an HTTP 429 (Too Many Requests) error response.  # Pagination The API provides `page` & `size` query params. `page` is a page number starting from 0. `size` is number of elements per page. Maximum value of `size` is 50.  Every paginated endpoints will have following response format: ``` {   \"content\": [     { ... },     { ... }   ],   \"number\": 0, // page number   \"size\": 10, // page size   \"numberOfElements\": 10, // number of element in this current page   \"totalElements\": 100,   \"totalPages\": 10 } ```  # Search Query You can perform search operations in some endpoints by setting the query parameter. Query value parameter constructed with following format:  ```bash ?query=<key><operator><value>,<key><operator><value> ```  Explanations: | Format | Descriptions | |-|-| | `<key>` | Key name to search certain fields | | `<operator>`   | Operation to apply on certain fields.<br>Supported operators: `:` `<` `>` | | `<value>` | Value to apply on search. **Value should be encoded using URL encoder**. For examples:<br><br>Plain: `John Doe`<br>Encoded: `John%20Doe` | | `,` | AND operator |   For example, the `/core/v1/employees` endpoint has following search query. |Key                    |Supported Operators  |Notes  | |-----------------------|---------------------|-------| |identificationNumberIn | `:`                 |Equal operator with multiple values. Each value should separated with delimiters `;`| |name                   | `:`                 |Like operator| |startDate              | `:`<br/>`>`<br/>`<` |Equal<br>Greater than or equal to<br>Less than or equal to|  Clients can construct search query with these following variations:  1. Search an employee with ID number 1111 ```bash curl <base-url>/core/v1/employees?query=identificationNumberIn:1111 ``` 1. Search multiple employees with ID number 1111 and 2222 ```bash curl <base-url>/core/v1/employees?query=identificationNumberIn:1111;2222 ``` 1. Search employees with name `John Doe` ```bash curl <base-url>/core/v1/employees?query=name:John%20Doe ``` 1. Search all employees with start date between 2020-01-01 and 2020-12-31: ```bash curl <base-url>/core/v1/employees?query=startDate>2020-01-01,startDate<2020-12-31 ``` 

    The version of the OpenAPI document: 1.0.0
    Contact: support@catapa.com
    Generated by OpenAPI Generator (https://openapi-generator.tech)

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


from __future__ import annotations
from inspect import getfullargspec
import json
import pprint
import re  # noqa: F401
from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator
from typing import Any, Dict, Optional
from openapi_client.models.id_request import IdRequest
from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict
from typing_extensions import Literal, Self
from pydantic import Field

SHIFTPATTERNTEMPLATEDETAILITEMREQUESTSHIFT_ANY_OF_SCHEMAS = ["IdRequest", "object"]

class ShiftPatternTemplateDetailItemRequestShift(BaseModel):
    """
    ShiftPatternTemplateDetailItemRequestShift
    """

    # data type: object
    anyof_schema_1_validator: Optional[Dict[str, Any]] = None
    # data type: IdRequest
    anyof_schema_2_validator: Optional[IdRequest] = None
    if TYPE_CHECKING:
        actual_instance: Optional[Union[IdRequest, object]] = None
    else:
        actual_instance: Any = None
    any_of_schemas: Set[str] = { "IdRequest", "object" }

    model_config = {
        "validate_assignment": True,
        "protected_namespaces": (),
    }

    def __init__(self, *args, **kwargs) -> None:
        if args:
            if len(args) > 1:
                raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`")
            if kwargs:
                raise ValueError("If a position argument is used, keyword arguments cannot be used.")
            super().__init__(actual_instance=args[0])
        else:
            super().__init__(**kwargs)

    @field_validator('actual_instance')
    def actual_instance_must_validate_anyof(cls, v):
        instance = ShiftPatternTemplateDetailItemRequestShift.model_construct()
        error_messages = []
        # validate data type: object
        try:
            instance.anyof_schema_1_validator = v
            return v
        except (ValidationError, ValueError) as e:
            error_messages.append(str(e))
        # validate data type: IdRequest
        if not isinstance(v, IdRequest):
            error_messages.append(f"Error! Input type `{type(v)}` is not `IdRequest`")
        else:
            return v

        if error_messages:
            # no match
            raise ValueError("No match found when setting the actual_instance in ShiftPatternTemplateDetailItemRequestShift with anyOf schemas: IdRequest, object. Details: " + ", ".join(error_messages))
        else:
            return v

    @classmethod
    def from_dict(cls, obj: Dict[str, Any]) -> Self:
        return cls.from_json(json.dumps(obj))

    @classmethod
    def from_json(cls, json_str: str) -> Self:
        """Returns the object represented by the json string"""
        instance = cls.model_construct()
        error_messages = []
        # deserialize data into object
        try:
            # validation
            instance.anyof_schema_1_validator = json.loads(json_str)
            # assign value to actual_instance
            instance.actual_instance = instance.anyof_schema_1_validator
            return instance
        except (ValidationError, ValueError) as e:
            error_messages.append(str(e))
        # anyof_schema_2_validator: Optional[IdRequest] = None
        try:
            instance.actual_instance = IdRequest.from_json(json_str)
            return instance
        except (ValidationError, ValueError) as e:
             error_messages.append(str(e))

        if error_messages:
            # no match
            raise ValueError("No match found when deserializing the JSON string into ShiftPatternTemplateDetailItemRequestShift with anyOf schemas: IdRequest, object. Details: " + ", ".join(error_messages))
        else:
            return instance

    def to_json(self) -> str:
        """Returns the JSON representation of the actual instance"""
        if self.actual_instance is None:
            return "null"

        if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json):
            return self.actual_instance.to_json()
        else:
            return json.dumps(self.actual_instance)

    def to_dict(self) -> Optional[Union[Dict[str, Any], IdRequest, object]]:
        """Returns the dict representation of the actual instance"""
        if self.actual_instance is None:
            return None

        if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict):
            return self.actual_instance.to_dict()
        else:
            return self.actual_instance

    def to_str(self) -> str:
        """Returns the string representation of the actual instance"""
        return pprint.pformat(self.model_dump())


