# coding: utf-8

"""
    Optimeering

    No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)

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

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


from __future__ import annotations

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

import optimeering_beta
from optimeering_beta.models.predictions_created_series import PredictionsCreatedSeries
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr
from typing_extensions import Self


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

    items: List[PredictionsCreatedSeries]
    next_page: Optional[StrictStr] = Field(default=None, description="The next page of results (if available).")
    _client: Any = None
    __properties: ClassVar[List[str]] = ["items", "next_page"]

    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 PredictionsSeriesGetResponse 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 each item in items (list)
        _items = []
        if self.items:
            for _item in self.items:
                if _item:
                    _items.append(_item.to_dict())
            _dict["items"] = _items
        return _dict

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

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

        _obj = cls.model_validate(
            {
                "items": [PredictionsCreatedSeries.from_dict(_item) for _item in obj["items"]]
                if obj.get("items") is not None
                else None,
                "next_page": obj.get("next_page"),
            }
        )
        return _obj

    @property
    def series_ids(self) -> List[int]:
        """Returns all the series ids included in the response"""
        iterate_over: Iterable
        if "items" in self.model_fields:
            iterate_over = self.items
        else:
            iterate_over = self
        return list({getattr(i, "id") for i in iterate_over})

    def datapoints(
        self,
        start: Optional[datetime | StrictStr] = None,
        end: Optional[datetime | StrictStr] = None,
        include_history: Optional[StrictBool] = None,
    ) -> optimeering_beta.models.PredictionsDataGetResponse:
        """
        Returns data points associated with

        :param start: The first datetime to fetch (inclusive). Defaults to current time. Should be specified in ISO 8601 format (eg - '2024-05-15T06:00:00+00:00'). Also supports delta formats (e.g. H+1,D-1,W-1)
        :param end: The last datetime to fetch (exclusive). Defaults to 2099-12-30. Should be specified in ISO 8601 format (eg - '2024-05-15T08:00:00+00:00'). Also supports delta formats (e.g. H+1,D-1,W-1)
        :param include_history: Include historical data into the response. Defaults to False. This argument has no effect if the underlying API does not support getting history.
        """
        if self._client is None:
            raise AttributeError("Cannot call datapoints method on this instance. The client has not been setup.")
        method_for_operation = optimeering_beta.PredictionsApi(api_client=self._client).get_predictions

        extra_params: Dict[str, Any] = {}
        valid_arguments = list(inspect.signature(method_for_operation).parameters.keys())
        if "include_history" in valid_arguments:
            extra_params["include_history"] = include_history

        return method_for_operation(series_id=self.series_ids, start=start, end=end, **extra_params)

    def __iter__(self):
        """Iteration method for generated models"""
        if isinstance(self, list):
            return (i for i in self)
        elif "items" in self.model_fields:
            return iter(self.items)
        else:
            raise AttributeError("This object does not support iteration.")
