# coding: utf-8

"""
    The Jira Cloud platform REST API

    Jira Cloud platform REST API documentation

    The version of the OpenAPI document: 1001.0.0-SNAPSHOT-7ce0ee67a52d004425175cea962ad1c1c7200181
    Contact: ecosystem@atlassian.com
    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 datetime
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from jira_client.models.filter_subscriptions_list import FilterSubscriptionsList
from jira_client.models.share_permission import SharePermission
from jira_client.models.user import User
from jira_client.models.user_list import UserList
from typing import Optional, Set
from typing_extensions import Self

class Filter(BaseModel):
    """
    Details about a filter.
    """ # noqa: E501
    approximate_last_used: Optional[datetime] = Field(default=None, description="\\[Experimental\\] Approximate last used time. Returns the date and time when the filter was last used. Returns `null` if the filter hasn't been used after tracking was enabled. For performance reasons, timestamps aren't updated in real time and therefore may not be exactly accurate.", alias="approximateLastUsed")
    description: Optional[StrictStr] = Field(default=None, description="A description of the filter.")
    edit_permissions: Optional[List[SharePermission]] = Field(default=None, description="The groups and projects that can edit the filter.", alias="editPermissions")
    favourite: Optional[StrictBool] = Field(default=None, description="Whether the filter is selected as a favorite.")
    favourited_count: Optional[StrictInt] = Field(default=None, description="The count of how many users have selected this filter as a favorite, including the filter owner.", alias="favouritedCount")
    id: Optional[StrictStr] = Field(default=None, description="The unique identifier for the filter.")
    jql: Optional[StrictStr] = Field(default=None, description="The JQL query for the filter. For example, *project = SSP AND issuetype = Bug*.")
    name: StrictStr = Field(description="The name of the filter. Must be unique.")
    owner: Optional[User] = Field(default=None, description="The user who owns the filter. This is defaulted to the creator of the filter, however Jira administrators can change the owner of a shared filter in the admin settings.")
    search_url: Optional[StrictStr] = Field(default=None, description="A URL to view the filter results in Jira, using the [Search for issues using JQL](#api-rest-api-3-filter-search-get) operation with the filter's JQL string to return the filter results. For example, *https://your-domain.atlassian.net/rest/api/3/search?jql=project+%3D+SSP+AND+issuetype+%3D+Bug*.", alias="searchUrl")
    var_self: Optional[StrictStr] = Field(default=None, description="The URL of the filter.", alias="self")
    share_permissions: Optional[List[SharePermission]] = Field(default=None, description="The groups and projects that the filter is shared with.", alias="sharePermissions")
    shared_users: Optional[UserList] = Field(default=None, description="A paginated list of the users that the filter is shared with. This includes users that are members of the groups or can browse the projects that the filter is shared with.", alias="sharedUsers")
    subscriptions: Optional[FilterSubscriptionsList] = Field(default=None, description="A paginated list of the users that are subscribed to the filter.")
    view_url: Optional[StrictStr] = Field(default=None, description="A URL to view the filter results in Jira, using the ID of the filter. For example, *https://your-domain.atlassian.net/issues/?filter=10100*.", alias="viewUrl")
    __properties: ClassVar[List[str]] = ["approximateLastUsed", "description", "editPermissions", "favourite", "favouritedCount", "id", "jql", "name", "owner", "searchUrl", "self", "sharePermissions", "sharedUsers", "subscriptions", "viewUrl"]

    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 Filter 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.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        """
        excluded_fields: Set[str] = set([
            "approximate_last_used",
            "favourited_count",
            "id",
            "owner",
            "search_url",
            "var_self",
            "shared_users",
            "subscriptions",
            "view_url",
        ])

        _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 edit_permissions (list)
        _items = []
        if self.edit_permissions:
            for _item_edit_permissions in self.edit_permissions:
                if _item_edit_permissions:
                    _items.append(_item_edit_permissions.to_dict())
            _dict['editPermissions'] = _items
        # override the default output from pydantic by calling `to_dict()` of owner
        if self.owner:
            _dict['owner'] = self.owner.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in share_permissions (list)
        _items = []
        if self.share_permissions:
            for _item_share_permissions in self.share_permissions:
                if _item_share_permissions:
                    _items.append(_item_share_permissions.to_dict())
            _dict['sharePermissions'] = _items
        # override the default output from pydantic by calling `to_dict()` of shared_users
        if self.shared_users:
            _dict['sharedUsers'] = self.shared_users.to_dict()
        # override the default output from pydantic by calling `to_dict()` of subscriptions
        if self.subscriptions:
            _dict['subscriptions'] = self.subscriptions.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "approximateLastUsed": obj.get("approximateLastUsed"),
            "description": obj.get("description"),
            "editPermissions": [SharePermission.from_dict(_item) for _item in obj["editPermissions"]] if obj.get("editPermissions") is not None else None,
            "favourite": obj.get("favourite"),
            "favouritedCount": obj.get("favouritedCount"),
            "id": obj.get("id"),
            "jql": obj.get("jql"),
            "name": obj.get("name"),
            "owner": User.from_dict(obj["owner"]) if obj.get("owner") is not None else None,
            "searchUrl": obj.get("searchUrl"),
            "self": obj.get("self"),
            "sharePermissions": [SharePermission.from_dict(_item) for _item in obj["sharePermissions"]] if obj.get("sharePermissions") is not None else None,
            "sharedUsers": UserList.from_dict(obj["sharedUsers"]) if obj.get("sharedUsers") is not None else None,
            "subscriptions": FilterSubscriptionsList.from_dict(obj["subscriptions"]) if obj.get("subscriptions") is not None else None,
            "viewUrl": obj.get("viewUrl")
        })
        return _obj


