# coding: utf-8

"""
    DUPR Backend APIs

    Internal RESTful APIs to access DUPR ratings, users and provide matches.

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

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


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from dupr_backend.models.basic_user_info import BasicUserInfo
from dupr_backend.models.score_format import ScoreFormat
from dupr_backend.models.team import Team
from typing import Optional, Set
from typing_extensions import Self

class Match(BaseModel):
    """
    Match
    """ # noqa: E501
    id: Optional[StrictInt] = None
    user_id: Optional[StrictInt] = Field(default=None, alias="userId")
    venue: Optional[StrictStr] = None
    location: StrictStr
    match_score_added: StrictBool = Field(alias="matchScoreAdded")
    tournament: Optional[StrictStr] = None
    league: Optional[StrictStr] = None
    event_date: date = Field(alias="eventDate")
    event_format: StrictStr = Field(alias="eventFormat")
    score_format: Optional[ScoreFormat] = Field(default=None, alias="scoreFormat")
    confirmed: StrictBool
    confirmation_threshold: StrictInt = Field(alias="confirmationThreshold")
    teams: List[Team]
    status: Optional[StrictStr] = None
    modified: Optional[datetime] = None
    created: Optional[datetime] = None
    event: Optional[StrictStr] = None
    match_source: Optional[StrictStr] = Field(default=None, alias="matchSource")
    club_id: Optional[StrictInt] = Field(default=None, alias="clubId")
    league_id: Optional[StrictInt] = Field(default=None, alias="leagueId")
    bracket_id: Optional[StrictInt] = Field(default=None, alias="bracketId")
    league_match_id: Optional[StrictInt] = Field(default=None, alias="leagueMatchId")
    match_type: Optional[StrictStr] = Field(default=None, alias="matchType")
    used_in_initialization: StrictBool = Field(alias="usedInInitialization")
    elo_calculated: Optional[StrictBool] = Field(default=None, alias="eloCalculated")
    validator: Optional[BasicUserInfo] = None
    creator: Optional[BasicUserInfo] = None
    client_id: Optional[StrictInt] = Field(default=None, alias="clientId")
    club_name: Optional[StrictStr] = Field(default=None, alias="clubName")
    client_name: Optional[StrictStr] = Field(default=None, alias="clientName")
    is_pro_match: StrictBool = Field(alias="isProMatch")
    player_ids: List[StrictInt] = Field(alias="playerIds")
    is_elo_rated_match: StrictBool = Field(alias="isEloRatedMatch")
    is_pre_elo_match: StrictBool = Field(alias="isPreEloMatch")
    __properties: ClassVar[List[str]] = ["id", "userId", "venue", "location", "matchScoreAdded", "tournament", "league", "eventDate", "eventFormat", "scoreFormat", "confirmed", "confirmationThreshold", "teams", "status", "modified", "created", "event", "matchSource", "clubId", "leagueId", "bracketId", "leagueMatchId", "matchType", "usedInInitialization", "eloCalculated", "validator", "creator", "clientId", "clubName", "clientName", "isProMatch", "playerIds", "isEloRatedMatch", "isPreEloMatch"]

    @field_validator('event_format')
    def event_format_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['SINGLES', 'DOUBLES']):
            raise ValueError("must be one of enum values ('SINGLES', 'DOUBLES')")
        return value

    @field_validator('status')
    def status_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(['ACTIVE', 'INACTIVE', 'UPCOMING', 'IN_PROGRESS', 'COMPLETE', 'CANCELLED', 'NOT_CONFIRMED', 'INVITED', 'CONFIRMED', 'MATCH_BYE', 'PENDING', 'FORFEITED', 'DELETED', 'ONGOING', 'SUSPENDED_TOS_13']):
            raise ValueError("must be one of enum values ('ACTIVE', 'INACTIVE', 'UPCOMING', 'IN_PROGRESS', 'COMPLETE', 'CANCELLED', 'NOT_CONFIRMED', 'INVITED', 'CONFIRMED', 'MATCH_BYE', 'PENDING', 'FORFEITED', 'DELETED', 'ONGOING', 'SUSPENDED_TOS_13')")
        return value

    @field_validator('match_source')
    def match_source_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(['DUPR', 'MANUAL', 'TOURNAMENT', 'CLUB', 'LEAGUE', 'PARTNER', 'EXTERNAL']):
            raise ValueError("must be one of enum values ('DUPR', 'MANUAL', 'TOURNAMENT', 'CLUB', 'LEAGUE', 'PARTNER', 'EXTERNAL')")
        return value

    @field_validator('match_type')
    def match_type_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(['SIDE_ONLY', 'RALLY']):
            raise ValueError("must be one of enum values ('SIDE_ONLY', 'RALLY')")
        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 Match 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 score_format
        if self.score_format:
            _dict['scoreFormat'] = self.score_format.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in teams (list)
        _items = []
        if self.teams:
            for _item_teams in self.teams:
                if _item_teams:
                    _items.append(_item_teams.to_dict())
            _dict['teams'] = _items
        # override the default output from pydantic by calling `to_dict()` of validator
        if self.validator:
            _dict['validator'] = self.validator.to_dict()
        # override the default output from pydantic by calling `to_dict()` of creator
        if self.creator:
            _dict['creator'] = self.creator.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "id": obj.get("id"),
            "userId": obj.get("userId"),
            "venue": obj.get("venue"),
            "location": obj.get("location"),
            "matchScoreAdded": obj.get("matchScoreAdded"),
            "tournament": obj.get("tournament"),
            "league": obj.get("league"),
            "eventDate": obj.get("eventDate"),
            "eventFormat": obj.get("eventFormat"),
            "scoreFormat": ScoreFormat.from_dict(obj["scoreFormat"]) if obj.get("scoreFormat") is not None else None,
            "confirmed": obj.get("confirmed"),
            "confirmationThreshold": obj.get("confirmationThreshold"),
            "teams": [Team.from_dict(_item) for _item in obj["teams"]] if obj.get("teams") is not None else None,
            "status": obj.get("status"),
            "modified": obj.get("modified"),
            "created": obj.get("created"),
            "event": obj.get("event"),
            "matchSource": obj.get("matchSource"),
            "clubId": obj.get("clubId"),
            "leagueId": obj.get("leagueId"),
            "bracketId": obj.get("bracketId"),
            "leagueMatchId": obj.get("leagueMatchId"),
            "matchType": obj.get("matchType"),
            "usedInInitialization": obj.get("usedInInitialization"),
            "eloCalculated": obj.get("eloCalculated"),
            "validator": BasicUserInfo.from_dict(obj["validator"]) if obj.get("validator") is not None else None,
            "creator": BasicUserInfo.from_dict(obj["creator"]) if obj.get("creator") is not None else None,
            "clientId": obj.get("clientId"),
            "clubName": obj.get("clubName"),
            "clientName": obj.get("clientName"),
            "isProMatch": obj.get("isProMatch"),
            "playerIds": obj.get("playerIds"),
            "isEloRatedMatch": obj.get("isEloRatedMatch"),
            "isPreEloMatch": obj.get("isPreEloMatch")
        })
        return _obj


