"""
Fitbit Web API Explorer

Fitbit provides a Web API for accessing data from Fitbit activity trackers, Aria scale, and manually entered logs. Anyone can develop an application to access and modify a Fitbit user's data on their behalf, so long as it complies with Fitbit Platform Terms of Service. These Swagger UI docs do not currently support making Fitbit API requests directly. In order to make a request, construct a request for the appropriate endpoint using this documentation, and then add an Authorization header to each request with an access token obtained using the steps outlined here: https://dev.fitbit.com/build/reference/web-api/developer-guide/authorization/.

The version of the OpenAPI document: 1
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, Union

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

from fitbit_web_api.models.sleep_log_levels import SleepLogLevels


class SleepLog(BaseModel):
    """
    SleepLog
    """

    date_of_sleep: Optional[date] = Field(
        default=None, description="The date the sleep log ended.", alias="dateOfSleep"
    )
    duration: Optional[StrictInt] = Field(
        default=None, description="Length of the sleep in milliseconds."
    )
    efficiency: Optional[Union[StrictFloat, StrictInt]] = Field(
        default=None, description="Calculated sleep efficiency score."
    )
    end_time: Optional[StrictStr] = Field(
        default=None, description="Time the sleep log ended.", alias="endTime"
    )
    info_code: Optional[StrictInt] = Field(
        default=None,
        description="An integer value representing the quality of data collected within the sleep log. 0 = Sufficient data, 1 = Insufficient heart rate data, 2 = Sleep period too short, 3 = Server-side issue.",
        alias="infoCode",
    )
    is_main_sleep: Optional[StrictBool] = Field(
        default=None,
        description="Boolean value indicating if this is the main sleep period.",
        alias="isMainSleep",
    )
    levels: Optional[SleepLogLevels] = None
    log_id: Optional[StrictInt] = Field(
        default=None, description="Sleep log ID.", alias="logId"
    )
    minutes_after_wakeup: Optional[StrictInt] = Field(
        default=None,
        description="The total number of minutes after the user woke up.",
        alias="minutesAfterWakeup",
    )
    minutes_asleep: Optional[StrictInt] = Field(
        default=None,
        description="The total number of minutes the user was asleep.",
        alias="minutesAsleep",
    )
    minutes_awake: Optional[StrictInt] = Field(
        default=None,
        description="The total sum of wake minutes only.",
        alias="minutesAwake",
    )
    minutes_to_fall_asleep: Optional[StrictInt] = Field(
        default=None,
        description="The total number of minutes before the user falls asleep.",
        alias="minutesToFallAsleep",
    )
    log_type: Optional[StrictStr] = Field(
        default=None,
        description="The type of sleep in terms of how it was logged.",
        alias="logType",
    )
    start_time: Optional[StrictStr] = Field(
        default=None, description="Time the sleep log begins.", alias="startTime"
    )
    time_in_bed: Optional[StrictInt] = Field(
        default=None,
        description="Total number of minutes the user was in bed.",
        alias="timeInBed",
    )
    type: Optional[StrictStr] = Field(
        default=None, description="The type of sleep log."
    )
    __properties: ClassVar[List[str]] = [
        "dateOfSleep",
        "duration",
        "efficiency",
        "endTime",
        "infoCode",
        "isMainSleep",
        "levels",
        "logId",
        "minutesAfterWakeup",
        "minutesAsleep",
        "minutesAwake",
        "minutesToFallAsleep",
        "logType",
        "startTime",
        "timeInBed",
        "type",
    ]

    @field_validator("log_type")
    def log_type_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(["auto_detected", "manual"]):
            raise ValueError("must be one of enum values ('auto_detected', 'manual')")
        return value

    @field_validator("type")
    def type_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(["classic", "stages"]):
            raise ValueError("must be one of enum values ('classic', 'stages')")
        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 SleepLog 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 levels
        if self.levels:
            _dict["levels"] = self.levels.to_dict()
        return _dict

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

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

        _obj = cls.model_validate(
            {
                "dateOfSleep": obj.get("dateOfSleep"),
                "duration": obj.get("duration"),
                "efficiency": obj.get("efficiency"),
                "endTime": obj.get("endTime"),
                "infoCode": obj.get("infoCode"),
                "isMainSleep": obj.get("isMainSleep"),
                "levels": SleepLogLevels.from_dict(obj["levels"])
                if obj.get("levels") is not None
                else None,
                "logId": obj.get("logId"),
                "minutesAfterWakeup": obj.get("minutesAfterWakeup"),
                "minutesAsleep": obj.get("minutesAsleep"),
                "minutesAwake": obj.get("minutesAwake"),
                "minutesToFallAsleep": obj.get("minutesToFallAsleep"),
                "logType": obj.get("logType"),
                "startTime": obj.get("startTime"),
                "timeInBed": obj.get("timeInBed"),
                "type": obj.get("type"),
            }
        )
        return _obj
