# coding: utf-8

"""
    Jellyfin API

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

    The version of the OpenAPI document: 10.11.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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from openapi_client.models.cast_receiver_application import CastReceiverApplication
from openapi_client.models.image_resolution import ImageResolution
from openapi_client.models.image_saving_convention import ImageSavingConvention
from openapi_client.models.metadata_options import MetadataOptions
from openapi_client.models.name_value_pair import NameValuePair
from openapi_client.models.path_substitution import PathSubstitution
from openapi_client.models.repository_info import RepositoryInfo
from openapi_client.models.trickplay_options import TrickplayOptions
from typing import Optional, Set
from typing_extensions import Self

class ServerConfiguration(BaseModel):
    """
    Represents the server configuration.
    """ # noqa: E501
    log_file_retention_days: Optional[StrictInt] = Field(default=None, description="Gets or sets the number of days we should retain log files.", alias="LogFileRetentionDays")
    is_startup_wizard_completed: Optional[StrictBool] = Field(default=None, description="Gets or sets a value indicating whether this instance is first run.", alias="IsStartupWizardCompleted")
    cache_path: Optional[StrictStr] = Field(default=None, description="Gets or sets the cache path.", alias="CachePath")
    previous_version: Optional[StrictStr] = Field(default=None, description="Gets or sets the last known version that was ran using the configuration.", alias="PreviousVersion")
    previous_version_str: Optional[StrictStr] = Field(default=None, description="Gets or sets the stringified PreviousVersion to be stored/loaded,  because System.Version itself isn't xml-serializable.", alias="PreviousVersionStr")
    enable_metrics: Optional[StrictBool] = Field(default=None, description="Gets or sets a value indicating whether to enable prometheus metrics exporting.", alias="EnableMetrics")
    enable_normalized_item_by_name_ids: Optional[StrictBool] = Field(default=None, alias="EnableNormalizedItemByNameIds")
    is_port_authorized: Optional[StrictBool] = Field(default=None, description="Gets or sets a value indicating whether this instance is port authorized.", alias="IsPortAuthorized")
    quick_connect_available: Optional[StrictBool] = Field(default=None, description="Gets or sets a value indicating whether quick connect is available for use on this server.", alias="QuickConnectAvailable")
    enable_case_sensitive_item_ids: Optional[StrictBool] = Field(default=None, description="Gets or sets a value indicating whether [enable case-sensitive item ids].", alias="EnableCaseSensitiveItemIds")
    disable_live_tv_channel_user_data_name: Optional[StrictBool] = Field(default=None, alias="DisableLiveTvChannelUserDataName")
    metadata_path: Optional[StrictStr] = Field(default=None, description="Gets or sets the metadata path.", alias="MetadataPath")
    preferred_metadata_language: Optional[StrictStr] = Field(default=None, description="Gets or sets the preferred metadata language.", alias="PreferredMetadataLanguage")
    metadata_country_code: Optional[StrictStr] = Field(default=None, description="Gets or sets the metadata country code.", alias="MetadataCountryCode")
    sort_replace_characters: Optional[List[StrictStr]] = Field(default=None, description="Gets or sets characters to be replaced with a ' ' in strings to create a sort name.", alias="SortReplaceCharacters")
    sort_remove_characters: Optional[List[StrictStr]] = Field(default=None, description="Gets or sets characters to be removed from strings to create a sort name.", alias="SortRemoveCharacters")
    sort_remove_words: Optional[List[StrictStr]] = Field(default=None, description="Gets or sets words to be removed from strings to create a sort name.", alias="SortRemoveWords")
    min_resume_pct: Optional[StrictInt] = Field(default=None, description="Gets or sets the minimum percentage of an item that must be played in order for playstate to be updated.", alias="MinResumePct")
    max_resume_pct: Optional[StrictInt] = Field(default=None, description="Gets or sets the maximum percentage of an item that can be played while still saving playstate. If this percentage is crossed playstate will be reset to the beginning and the item will be marked watched.", alias="MaxResumePct")
    min_resume_duration_seconds: Optional[StrictInt] = Field(default=None, description="Gets or sets the minimum duration that an item must have in order to be eligible for playstate updates..", alias="MinResumeDurationSeconds")
    min_audiobook_resume: Optional[StrictInt] = Field(default=None, description="Gets or sets the minimum minutes of a book that must be played in order for playstate to be updated.", alias="MinAudiobookResume")
    max_audiobook_resume: Optional[StrictInt] = Field(default=None, description="Gets or sets the remaining minutes of a book that can be played while still saving playstate. If this percentage is crossed playstate will be reset to the beginning and the item will be marked watched.", alias="MaxAudiobookResume")
    inactive_session_threshold: Optional[StrictInt] = Field(default=None, description="Gets or sets the threshold in minutes after a inactive session gets closed automatically.  If set to 0 the check for inactive sessions gets disabled.", alias="InactiveSessionThreshold")
    library_monitor_delay: Optional[StrictInt] = Field(default=None, description="Gets or sets the delay in seconds that we will wait after a file system change to try and discover what has been added/removed  Some delay is necessary with some items because their creation is not atomic.  It involves the creation of several  different directories and files.", alias="LibraryMonitorDelay")
    library_update_duration: Optional[StrictInt] = Field(default=None, description="Gets or sets the duration in seconds that we will wait after a library updated event before executing the library changed notification.", alias="LibraryUpdateDuration")
    cache_size: Optional[StrictInt] = Field(default=None, description="Gets or sets the maximum amount of items to cache.", alias="CacheSize")
    image_saving_convention: Optional[ImageSavingConvention] = Field(default=None, description="Gets or sets the image saving convention.", alias="ImageSavingConvention")
    metadata_options: Optional[List[MetadataOptions]] = Field(default=None, alias="MetadataOptions")
    skip_deserialization_for_basic_types: Optional[StrictBool] = Field(default=None, alias="SkipDeserializationForBasicTypes")
    server_name: Optional[StrictStr] = Field(default=None, alias="ServerName")
    ui_culture: Optional[StrictStr] = Field(default=None, alias="UICulture")
    save_metadata_hidden: Optional[StrictBool] = Field(default=None, alias="SaveMetadataHidden")
    content_types: Optional[List[NameValuePair]] = Field(default=None, alias="ContentTypes")
    remote_client_bitrate_limit: Optional[StrictInt] = Field(default=None, alias="RemoteClientBitrateLimit")
    enable_folder_view: Optional[StrictBool] = Field(default=None, alias="EnableFolderView")
    enable_grouping_movies_into_collections: Optional[StrictBool] = Field(default=None, alias="EnableGroupingMoviesIntoCollections")
    enable_grouping_shows_into_collections: Optional[StrictBool] = Field(default=None, alias="EnableGroupingShowsIntoCollections")
    display_specials_within_seasons: Optional[StrictBool] = Field(default=None, alias="DisplaySpecialsWithinSeasons")
    codecs_used: Optional[List[StrictStr]] = Field(default=None, alias="CodecsUsed")
    plugin_repositories: Optional[List[RepositoryInfo]] = Field(default=None, alias="PluginRepositories")
    enable_external_content_in_suggestions: Optional[StrictBool] = Field(default=None, alias="EnableExternalContentInSuggestions")
    image_extraction_timeout_ms: Optional[StrictInt] = Field(default=None, alias="ImageExtractionTimeoutMs")
    path_substitutions: Optional[List[PathSubstitution]] = Field(default=None, alias="PathSubstitutions")
    enable_slow_response_warning: Optional[StrictBool] = Field(default=None, description="Gets or sets a value indicating whether slow server responses should be logged as a warning.", alias="EnableSlowResponseWarning")
    slow_response_threshold_ms: Optional[StrictInt] = Field(default=None, description="Gets or sets the threshold for the slow response time warning in ms.", alias="SlowResponseThresholdMs")
    cors_hosts: Optional[List[StrictStr]] = Field(default=None, description="Gets or sets the cors hosts.", alias="CorsHosts")
    activity_log_retention_days: Optional[StrictInt] = Field(default=None, description="Gets or sets the number of days we should retain activity logs.", alias="ActivityLogRetentionDays")
    library_scan_fanout_concurrency: Optional[StrictInt] = Field(default=None, description="Gets or sets the how the library scan fans out.", alias="LibraryScanFanoutConcurrency")
    library_metadata_refresh_concurrency: Optional[StrictInt] = Field(default=None, description="Gets or sets the how many metadata refreshes can run concurrently.", alias="LibraryMetadataRefreshConcurrency")
    allow_client_log_upload: Optional[StrictBool] = Field(default=None, description="Gets or sets a value indicating whether clients should be allowed to upload logs.", alias="AllowClientLogUpload")
    dummy_chapter_duration: Optional[StrictInt] = Field(default=None, description="Gets or sets the dummy chapter duration in seconds, use 0 (zero) or less to disable generation altogether.", alias="DummyChapterDuration")
    chapter_image_resolution: Optional[ImageResolution] = Field(default=None, description="Gets or sets the chapter image resolution.", alias="ChapterImageResolution")
    parallel_image_encoding_limit: Optional[StrictInt] = Field(default=None, description="Gets or sets the limit for parallel image encoding.", alias="ParallelImageEncodingLimit")
    cast_receiver_applications: Optional[List[CastReceiverApplication]] = Field(default=None, description="Gets or sets the list of cast receiver applications.", alias="CastReceiverApplications")
    trickplay_options: Optional[TrickplayOptions] = Field(default=None, description="Gets or sets the trickplay options.", alias="TrickplayOptions")
    enable_legacy_authorization: Optional[StrictBool] = Field(default=None, description="Gets or sets a value indicating whether old authorization methods are allowed.", alias="EnableLegacyAuthorization")
    __properties: ClassVar[List[str]] = ["LogFileRetentionDays", "IsStartupWizardCompleted", "CachePath", "PreviousVersion", "PreviousVersionStr", "EnableMetrics", "EnableNormalizedItemByNameIds", "IsPortAuthorized", "QuickConnectAvailable", "EnableCaseSensitiveItemIds", "DisableLiveTvChannelUserDataName", "MetadataPath", "PreferredMetadataLanguage", "MetadataCountryCode", "SortReplaceCharacters", "SortRemoveCharacters", "SortRemoveWords", "MinResumePct", "MaxResumePct", "MinResumeDurationSeconds", "MinAudiobookResume", "MaxAudiobookResume", "InactiveSessionThreshold", "LibraryMonitorDelay", "LibraryUpdateDuration", "CacheSize", "ImageSavingConvention", "MetadataOptions", "SkipDeserializationForBasicTypes", "ServerName", "UICulture", "SaveMetadataHidden", "ContentTypes", "RemoteClientBitrateLimit", "EnableFolderView", "EnableGroupingMoviesIntoCollections", "EnableGroupingShowsIntoCollections", "DisplaySpecialsWithinSeasons", "CodecsUsed", "PluginRepositories", "EnableExternalContentInSuggestions", "ImageExtractionTimeoutMs", "PathSubstitutions", "EnableSlowResponseWarning", "SlowResponseThresholdMs", "CorsHosts", "ActivityLogRetentionDays", "LibraryScanFanoutConcurrency", "LibraryMetadataRefreshConcurrency", "AllowClientLogUpload", "DummyChapterDuration", "ChapterImageResolution", "ParallelImageEncodingLimit", "CastReceiverApplications", "TrickplayOptions", "EnableLegacyAuthorization"]

    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 ServerConfiguration 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 metadata_options (list)
        _items = []
        if self.metadata_options:
            for _item_metadata_options in self.metadata_options:
                if _item_metadata_options:
                    _items.append(_item_metadata_options.to_dict())
            _dict['MetadataOptions'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in content_types (list)
        _items = []
        if self.content_types:
            for _item_content_types in self.content_types:
                if _item_content_types:
                    _items.append(_item_content_types.to_dict())
            _dict['ContentTypes'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in plugin_repositories (list)
        _items = []
        if self.plugin_repositories:
            for _item_plugin_repositories in self.plugin_repositories:
                if _item_plugin_repositories:
                    _items.append(_item_plugin_repositories.to_dict())
            _dict['PluginRepositories'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in path_substitutions (list)
        _items = []
        if self.path_substitutions:
            for _item_path_substitutions in self.path_substitutions:
                if _item_path_substitutions:
                    _items.append(_item_path_substitutions.to_dict())
            _dict['PathSubstitutions'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in cast_receiver_applications (list)
        _items = []
        if self.cast_receiver_applications:
            for _item_cast_receiver_applications in self.cast_receiver_applications:
                if _item_cast_receiver_applications:
                    _items.append(_item_cast_receiver_applications.to_dict())
            _dict['CastReceiverApplications'] = _items
        # override the default output from pydantic by calling `to_dict()` of trickplay_options
        if self.trickplay_options:
            _dict['TrickplayOptions'] = self.trickplay_options.to_dict()
        # set to None if cache_path (nullable) is None
        # and model_fields_set contains the field
        if self.cache_path is None and "cache_path" in self.model_fields_set:
            _dict['CachePath'] = None

        # set to None if previous_version (nullable) is None
        # and model_fields_set contains the field
        if self.previous_version is None and "previous_version" in self.model_fields_set:
            _dict['PreviousVersion'] = None

        # set to None if previous_version_str (nullable) is None
        # and model_fields_set contains the field
        if self.previous_version_str is None and "previous_version_str" in self.model_fields_set:
            _dict['PreviousVersionStr'] = None

        # set to None if activity_log_retention_days (nullable) is None
        # and model_fields_set contains the field
        if self.activity_log_retention_days is None and "activity_log_retention_days" in self.model_fields_set:
            _dict['ActivityLogRetentionDays'] = None

        return _dict

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

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

        _obj = cls.model_validate({
            "LogFileRetentionDays": obj.get("LogFileRetentionDays"),
            "IsStartupWizardCompleted": obj.get("IsStartupWizardCompleted"),
            "CachePath": obj.get("CachePath"),
            "PreviousVersion": obj.get("PreviousVersion"),
            "PreviousVersionStr": obj.get("PreviousVersionStr"),
            "EnableMetrics": obj.get("EnableMetrics"),
            "EnableNormalizedItemByNameIds": obj.get("EnableNormalizedItemByNameIds"),
            "IsPortAuthorized": obj.get("IsPortAuthorized"),
            "QuickConnectAvailable": obj.get("QuickConnectAvailable"),
            "EnableCaseSensitiveItemIds": obj.get("EnableCaseSensitiveItemIds"),
            "DisableLiveTvChannelUserDataName": obj.get("DisableLiveTvChannelUserDataName"),
            "MetadataPath": obj.get("MetadataPath"),
            "PreferredMetadataLanguage": obj.get("PreferredMetadataLanguage"),
            "MetadataCountryCode": obj.get("MetadataCountryCode"),
            "SortReplaceCharacters": obj.get("SortReplaceCharacters"),
            "SortRemoveCharacters": obj.get("SortRemoveCharacters"),
            "SortRemoveWords": obj.get("SortRemoveWords"),
            "MinResumePct": obj.get("MinResumePct"),
            "MaxResumePct": obj.get("MaxResumePct"),
            "MinResumeDurationSeconds": obj.get("MinResumeDurationSeconds"),
            "MinAudiobookResume": obj.get("MinAudiobookResume"),
            "MaxAudiobookResume": obj.get("MaxAudiobookResume"),
            "InactiveSessionThreshold": obj.get("InactiveSessionThreshold"),
            "LibraryMonitorDelay": obj.get("LibraryMonitorDelay"),
            "LibraryUpdateDuration": obj.get("LibraryUpdateDuration"),
            "CacheSize": obj.get("CacheSize"),
            "ImageSavingConvention": obj.get("ImageSavingConvention"),
            "MetadataOptions": [MetadataOptions.from_dict(_item) for _item in obj["MetadataOptions"]] if obj.get("MetadataOptions") is not None else None,
            "SkipDeserializationForBasicTypes": obj.get("SkipDeserializationForBasicTypes"),
            "ServerName": obj.get("ServerName"),
            "UICulture": obj.get("UICulture"),
            "SaveMetadataHidden": obj.get("SaveMetadataHidden"),
            "ContentTypes": [NameValuePair.from_dict(_item) for _item in obj["ContentTypes"]] if obj.get("ContentTypes") is not None else None,
            "RemoteClientBitrateLimit": obj.get("RemoteClientBitrateLimit"),
            "EnableFolderView": obj.get("EnableFolderView"),
            "EnableGroupingMoviesIntoCollections": obj.get("EnableGroupingMoviesIntoCollections"),
            "EnableGroupingShowsIntoCollections": obj.get("EnableGroupingShowsIntoCollections"),
            "DisplaySpecialsWithinSeasons": obj.get("DisplaySpecialsWithinSeasons"),
            "CodecsUsed": obj.get("CodecsUsed"),
            "PluginRepositories": [RepositoryInfo.from_dict(_item) for _item in obj["PluginRepositories"]] if obj.get("PluginRepositories") is not None else None,
            "EnableExternalContentInSuggestions": obj.get("EnableExternalContentInSuggestions"),
            "ImageExtractionTimeoutMs": obj.get("ImageExtractionTimeoutMs"),
            "PathSubstitutions": [PathSubstitution.from_dict(_item) for _item in obj["PathSubstitutions"]] if obj.get("PathSubstitutions") is not None else None,
            "EnableSlowResponseWarning": obj.get("EnableSlowResponseWarning"),
            "SlowResponseThresholdMs": obj.get("SlowResponseThresholdMs"),
            "CorsHosts": obj.get("CorsHosts"),
            "ActivityLogRetentionDays": obj.get("ActivityLogRetentionDays"),
            "LibraryScanFanoutConcurrency": obj.get("LibraryScanFanoutConcurrency"),
            "LibraryMetadataRefreshConcurrency": obj.get("LibraryMetadataRefreshConcurrency"),
            "AllowClientLogUpload": obj.get("AllowClientLogUpload"),
            "DummyChapterDuration": obj.get("DummyChapterDuration"),
            "ChapterImageResolution": obj.get("ChapterImageResolution"),
            "ParallelImageEncodingLimit": obj.get("ParallelImageEncodingLimit"),
            "CastReceiverApplications": [CastReceiverApplication.from_dict(_item) for _item in obj["CastReceiverApplications"]] if obj.get("CastReceiverApplications") is not None else None,
            "TrickplayOptions": TrickplayOptions.from_dict(obj["TrickplayOptions"]) if obj.get("TrickplayOptions") is not None else None,
            "EnableLegacyAuthorization": obj.get("EnableLegacyAuthorization")
        })
        return _obj


