# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from typing import Any, ClassVar, Literal, overload
from collections.abc import Callable, Generator

from openstack._utils import renamed_param
from openstack import exceptions
from openstack.identity.v3 import project as _project
from openstack.key_manager.v1 import container as _container
from openstack.key_manager.v1 import order as _order
from openstack.key_manager.v1 import project_quota as _project_quota
from openstack.key_manager.v1 import quota as _quota
from openstack.key_manager.v1 import secret as _secret
from openstack.key_manager.v1 import secret_acl as _secret_acl
from openstack.key_manager.v1 import secret_consumer as _secret_consumer
from openstack.key_manager.v1 import secret_store as _secret_store
from openstack import proxy
from openstack import resource


class Proxy(proxy.Proxy):
    api_version: ClassVar[Literal['1']] = '1'

    _resource_registry = {
        "container": _container.Container,
        "order": _order.Order,
        "project_quota": _project_quota.ProjectQuota,
        "secret": _secret.Secret,
        "secret_acl": _secret_acl.SecretACL,
        "secret_consumer": _secret_consumer.SecretConsumer,
        "secret_store": _secret_store.SecretStore,
    }

    def create_container(self, **attrs: Any) -> _container.Container:
        """Create a new container from attributes

        :param attrs: Keyword arguments which will be used to create
            a :class:`~openstack.key_manager.v1.container.Container`,
            comprised of the properties on the Container class.

        :returns: The results of container creation
        """
        return self._create(_container.Container, **attrs)

    def delete_container(
        self,
        container: str | _container.Container,
        ignore_missing: bool = True,
    ) -> None:
        """Delete a container

        :param container: The value can be either the ID of a container or a
            :class:`~openstack.key_manager.v1.container.Container`
            instance.
        :param ignore_missing: When set to ``False``
            :class:`~openstack.exceptions.NotFoundException` will be
            raised when the container does not exist.
            When set to ``True``, no exception will be set when
            attempting to delete a nonexistent container.

        :returns: ``None``
        """
        self._delete(
            _container.Container, container, ignore_missing=ignore_missing
        )

    @overload
    def find_container(
        self,
        name_or_id: str,
        ignore_missing: Literal[False],
    ) -> _container.Container: ...

    @overload
    def find_container(
        self,
        name_or_id: str,
        ignore_missing: bool = True,
    ) -> _container.Container | None: ...

    def find_container(
        self,
        name_or_id: str,
        ignore_missing: bool = True,
    ) -> _container.Container | None:
        """Find a single container

        :param name_or_id: The name or ID of a container.
        :param ignore_missing: When set to ``False``
            :class:`~openstack.exceptions.NotFoundException` will be
            raised when the resource does not exist.
            When set to ``True``, None will be returned when
            attempting to find a nonexistent resource.
        :returns: One :class:`~openstack.key_manager.v1.container.Container`
            or None
        """
        return self._find(
            _container.Container, name_or_id, ignore_missing=ignore_missing
        )

    def get_container(
        self, container: str | _container.Container
    ) -> _container.Container:
        """Get a single container

        :param container: The value can be the ID of a container or a
            :class:`~openstack.key_manager.v1.container.Container`
            instance.

        :returns: One :class:`~openstack.key_manager.v1.container.Container`
        :raises: :class:`~openstack.exceptions.NotFoundException`
            when no resource can be found.
        """
        return self._get(_container.Container, container)

    def containers(
        self,
        **query: Any,
    ) -> Generator[_container.Container, None, None]:
        """Return a generator of containers

        :param query: Optional query parameters to be sent to limit
            the resources being returned.

        :returns: A generator of container objects
        """
        return self._list(_container.Container, **query)

    def update_container(
        self, container: str | _container.Container, **attrs: Any
    ) -> _container.Container:
        """Update a container

        :param container: Either the id of a container or a
            :class:`~openstack.key_manager.v1.container.Container` instance.
        :param attrs: The attributes to update on the container represented
            by ``container``.

        :returns: The updated container
        """
        return self._update(_container.Container, container, **attrs)

    def create_order(self, **attrs: Any) -> _order.Order:
        """Create a new order from attributes

        :param attrs: Keyword arguments which will be used to create
            a :class:`~openstack.key_manager.v1.order.Order`,
            comprised of the properties on the Order class.

        :returns: The results of order creation
        """
        return self._create(_order.Order, **attrs)

    def delete_order(
        self, order: str | _order.Order, ignore_missing: bool = True
    ) -> None:
        """Delete an order

        :param order: The value can be either the ID of a order or a
            :class:`~openstack.key_manager.v1.order.Order`
            instance.
        :param ignore_missing: When set to ``False``
            :class:`~openstack.exceptions.NotFoundException` will be
            raised when the order does not exist.
            When set to ``True``, no exception will be set when
            attempting to delete a nonexistent order.

        :returns: ``None``
        """
        self._delete(_order.Order, order, ignore_missing=ignore_missing)

    @overload
    def find_order(
        self,
        name_or_id: str,
        ignore_missing: Literal[False],
    ) -> _order.Order: ...

    @overload
    def find_order(
        self,
        name_or_id: str,
        ignore_missing: bool = True,
    ) -> _order.Order | None: ...

    def find_order(
        self,
        name_or_id: str,
        ignore_missing: bool = True,
    ) -> _order.Order | None:
        """Find a single order

        :param name_or_id: The name or ID of a order.
        :param ignore_missing: When set to ``False``
            :class:`~openstack.exceptions.NotFoundException` will be
            raised when the resource does not exist.
            When set to ``True``, None will be returned when
            attempting to find a nonexistent resource.
        :returns: One :class:`~openstack.key_manager.v1.order.Order` or None
        """
        return self._find(
            _order.Order, name_or_id, ignore_missing=ignore_missing
        )

    def get_order(self, order: str | _order.Order) -> _order.Order:
        """Get a single order

        :param order: The value can be the ID of an order or a
            :class:`~openstack.key_manager.v1.order.Order`
            instance.

        :returns: One :class:`~openstack.key_manager.v1.order.Order`
        :raises: :class:`~openstack.exceptions.NotFoundException`
            when no resource can be found.
        """
        return self._get(_order.Order, order)

    def orders(self, **query: Any) -> Generator[_order.Order, None, None]:
        """Return a generator of orders

        :param query: Optional query parameters to be sent to limit
            the resources being returned.

        :returns: A generator of order objects
        """
        return self._list(_order.Order, **query)

    def update_order(
        self, order: str | _order.Order, **attrs: Any
    ) -> _order.Order:
        """Update a order

        :param order: Either the id of a order or a
            :class:`~openstack.key_manager.v1.order.Order` instance.
        :param attrs: The attributes to update on the order represented
            by ``order``.

        :returns: The updated order
        """
        return self._update(_order.Order, order, **attrs)

    def create_secret(self, **attrs: Any) -> _secret.Secret:
        """Create a new secret from attributes

        :param attrs: Keyword arguments which will be used to create a
            :class:`~openstack.key_manager.v1.secret.Secret`,
            comprised of the properties on the Order class.

        :returns: The results of secret creation
        """
        return self._create(_secret.Secret, **attrs)

    def delete_secret(
        self, secret: str | _secret.Secret, ignore_missing: bool = True
    ) -> None:
        """Delete a secret

        :param secret: The value can be either the ID of a secret or a
            :class:`~openstack.key_manager.v1.secret.Secret`
            instance.
        :param ignore_missing: When set to ``False``
            :class:`~openstack.exceptions.NotFoundException` will be
            raised when the secret does not exist.
            When set to ``True``, no exception will be set when
            attempting to delete a nonexistent secret.

        :returns: ``None``
        """
        self._delete(_secret.Secret, secret, ignore_missing=ignore_missing)

    @overload
    def find_secret(
        self,
        name_or_id: str,
        ignore_missing: Literal[False],
    ) -> _secret.Secret: ...

    @overload
    def find_secret(
        self,
        name_or_id: str,
        ignore_missing: bool = True,
    ) -> _secret.Secret | None: ...

    def find_secret(
        self,
        name_or_id: str,
        ignore_missing: bool = True,
    ) -> _secret.Secret | None:
        """Find a single secret

        :param name_or_id: The name or ID of a secret.
        :param ignore_missing: When set to ``False``
            :class:`~openstack.exceptions.NotFoundException` will be
            raised when the resource does not exist.
            When set to ``True``, None will be returned when
            attempting to find a nonexistent resource.
        :returns: One :class:`~openstack.key_manager.v1.secret.Secret` or
            None
        """
        return self._find(
            _secret.Secret, name_or_id, ignore_missing=ignore_missing
        )

    def get_secret(self, secret: str | _secret.Secret) -> _secret.Secret:
        """Get a single secret

        :param secret: The value can be the ID of a secret or a
            :class:`~openstack.key_manager.v1.secret.Secret`
            instance.

        :returns: One :class:`~openstack.key_manager.v1.secret.Secret`
        :raises: :class:`~openstack.exceptions.NotFoundException`
            when no resource can be found.
        """
        return self._get(_secret.Secret, secret)

    def secrets(self, **query: Any) -> Generator[_secret.Secret, None, None]:
        """Return a generator of secrets

        :param query: Optional query parameters to be sent to limit
            the resources being returned.

        :returns: A generator of secret objects
        """
        return self._list(_secret.Secret, **query)

    def update_secret(
        self, secret: str | _secret.Secret, **attrs: Any
    ) -> _secret.Secret:
        """Update a secret

        :param secret: Either the id of a secret or a
            :class:`~openstack.key_manager.v1.secret.Secret` instance.
        :param attrs: The attributes to update on the secret represented
            by ``secret``.

        :returns: The updated secret
        """
        return self._update(_secret.Secret, secret, **attrs)

    # ========== Secret Store Operations ==========

    def secret_stores(
        self,
        **query: Any,
    ) -> Generator[_secret_store.SecretStore, None, None]:
        """Return a generator of secret stores

        :param query: Optional query parameters to be sent to limit
            the resources being returned.

        :returns: A generator of secret store objects
        """
        return self._list(_secret_store.SecretStore, **query)

    def get_global_default_secret_store(self) -> _secret_store.SecretStore:
        """Get the global default secret store

        :returns: One
            :class:`~openstack.key_manager.v1.secret_store.SecretStore`
        :raises: :class:`~openstack.exceptions.NotFoundException`
            when no resource can be found.
        """
        return self._get(_secret_store.SecretStore, 'global-default')

    def get_preferred_secret_store(self) -> _secret_store.SecretStore:
        """Get the preferred secret store for the current project

        :returns: One
            :class:`~openstack.key_manager.v1.secret_store.SecretStore`
        :raises: :class:`~openstack.exceptions.NotFoundException`
            when no resource can be found.
        """
        return self._get(_secret_store.SecretStore, 'preferred')

    @renamed_param('project_id', 'project')
    def delete_project_quota(
        self,
        project: str | _project.Project,
        ignore_missing: bool = True,
    ) -> None:
        """Delete a project quota

        :param project: A project ID or
            :class:`~openstack.identity.v3.project.Project` instance.
        :param ignore_missing: When set to ``False``
            :class:`~openstack.exceptions.NotFoundException` will be
            raised when the project quota does not exist.
            When set to ``True``, no exception will be set when
            attempting to delete a nonexistent project quota.

        :returns: ``None``
        """
        self._delete(
            _project_quota.ProjectQuota,
            resource.Resource._get_id(project),
            ignore_missing=ignore_missing,
        )

    @renamed_param('project_id', 'project')
    def get_project_quota(
        self, project: str | _project.Project
    ) -> _project_quota.ProjectQuota:
        """Get a single project quota

        :param project: A project ID or
            :class:`~openstack.identity.v3.project.Project` instance.

        :returns: One
            :class:`~openstack.key_manager.v1.project_quota.ProjectQuota`
        :raises: :class:`~openstack.exceptions.NotFoundException`
            when no resource can be found.
        """
        return self._get(
            _project_quota.ProjectQuota, resource.Resource._get_id(project)
        )

    @renamed_param('project_id', 'project')
    def update_project_quota(
        self, project: str | _project.Project, **attrs: Any
    ) -> _project_quota.ProjectQuota:
        """Update a project quota

        :param project: A project ID or
            :class:`~openstack.identity.v3.project.Project` instance.
        :param attrs: The attributes to update on the project quota represented
            by ``project quota``.

        :returns: The updated project quota
        """
        return self._update(
            _project_quota.ProjectQuota,
            resource.Resource._get_id(project),
            **attrs,
        )

    def get_quota(self) -> _quota.Quota:
        """Get the effective quotas for the current project

        :returns: One :class:`~openstack.key_manager.v1.quota.Quota`
        :raises: :class:`~openstack.exceptions.NotFoundException`
            when no resource can be found.
        """
        return self._get(_quota.Quota, requires_id=False)

    # ========== Secret ACL Operations ==========

    def get_secret_acl(
        self, secret: str | _secret.Secret
    ) -> _secret_acl.SecretACL:
        """Get the ACL of a secret.

        :param secret: Secret ID or a
            :class:`~openstack.key_manager.v1.secret.Secret` instance.
        :returns: :class:`~openstack.key_manager.v1.secret_acl.SecretACL`
            whose ``read`` contains the ACL. If no explicit ACL exists,
            the default ACL is returned.
        :raises: :class:`~openstack.exceptions.NotFoundException`
        """
        sid = resource.Resource._get_id(secret)
        return self._get(
            _secret_acl.SecretACL,
            None,
            requires_id=False,
            path_args={"secret_id": sid},
        )

    def set_secret_acl(
        self, secret: str | _secret.Secret, **attrs: Any
    ) -> _secret_acl.SecretACL:
        """Set (replace) the ACL of a secret (PUT).

        :param secret: Secret ID or Secret instance.
        :param attrs: ACL body, typically a ``read`` dict.
        :returns: :class:`~openstack.key_manager.v1.secret_acl.SecretACL`
            whose ``acl_ref`` references the ACL URL.
        """
        sid = resource.Resource._get_id(secret)
        return self._update(
            _secret_acl.SecretACL,
            None,
            requires_id=False,
            path_args={"secret_id": sid},
            method="PUT",
            **attrs,
        )

    def update_secret_acl(
        self, secret: str | _secret.Secret, **attrs: Any
    ) -> _secret_acl.SecretACL:
        """Partially update the ACL of a secret (PATCH).

        :param secret: Secret ID or Secret instance.
        :param attrs: Partial ACL body, typically a ``read`` dict.
        :returns: :class:`~openstack.key_manager.v1.secret_acl.SecretACL`
            whose ``acl_ref`` references the ACL URL.
        """
        sid = resource.Resource._get_id(secret)
        return self._update(
            _secret_acl.SecretACL,
            None,
            requires_id=False,
            path_args={"secret_id": sid},
            method="PATCH",
            **attrs,
        )

    def delete_secret_acl(
        self, secret: _secret.Secret, ignore_missing: bool = True
    ) -> _secret_acl.SecretACL | None:
        """Delete the ACL of a secret.

        :param secret: Secret ID or Secret instance.
        :param ignore_missing: When set to False, raise if not found.
        :returns: ``None``
        :raises: :class:`~openstack.exceptions.NotFoundException`
        """
        sid = resource.Resource._get_id(secret)
        return self._delete(
            _secret_acl.SecretACL,
            None,
            requires_id=False,
            path_args={"secret_id": sid},
            ignore_missing=ignore_missing,
        )

    def create_secret_consumer(
        self, secret: str | _secret.Secret, **attrs: Any
    ) -> _secret_consumer.SecretConsumer:
        """Create a consumer for a secret

        :param secret: Either the id of a secret or a
            :class:`~openstack.key_manager.v1.secret.Secret` instance.
        :param attrs: Must include ``service``, ``resource_type``,
            ``resource_id``.
        :returns: The created consumer association
        """
        sid = resource.Resource._get_id(secret)
        if 'resource_type' in attrs:
            # 'resource_type' conflicts with proxy._create's parameter of the
            # same name, which refers to the resource class being created.
            attrs['__conflicting_attrs'] = {
                'resource_type': attrs.pop('resource_type')
            }
        return self._create(
            _secret_consumer.SecretConsumer, secret_id=sid, **attrs
        )

    def delete_secret_consumer(
        self,
        secret: str | _secret.Secret,
        ignore_missing: bool = True,
        **attrs: Any,
    ) -> None:
        """Delete a consumer association from a secret

        :param secret: Either the id of a secret or a
            :class:`~openstack.key_manager.v1.secret.Secret`
            instance.
        :param ignore_missing: When set to ``False``
            :class:`~openstack.exceptions.NotFoundException` will be
            raised when the secret does not exist.
            When set to ``True``, no exception will be set when
            attempting to delete a nonexistent secret.
        :param attrs: Must include ``service``, ``resource_type``,
            ``resource_id``.
        :returns: ``None``
        """
        sid = resource.Resource._get_id(secret)
        # proxy._delete does not support __conflicting_attrs, so we cannot
        # use it here as 'resource_type' in attrs conflicts with its first
        # parameter of the same name.
        consumer = _secret_consumer.SecretConsumer.new(secret_id=sid, **attrs)
        try:
            consumer.delete(self)
        except exceptions.NotFoundException:
            if ignore_missing:
                return None
            raise

    def secret_consumers(
        self, secret: str | _secret.Secret, **query: Any
    ) -> Generator[_secret_consumer.SecretConsumer, None, None]:
        """List consumers for a secret

        :param secret: Either the id of a secret or a
            :class:`~openstack.key_manager.v1.secret.Secret` instance.
        :returns: A generator of SecretConsumer objects
        """
        sid = resource.Resource._get_id(secret)

        return self._list(
            _secret_consumer.SecretConsumer, secret_id=sid, **query
        )

    # ========== Utilities ==========

    def wait_for_status(
        self,
        res: resource.ResourceT,
        status: str,
        failures: list[str] | None = None,
        interval: int | float | None = 2,
        wait: int | None = None,
        attribute: str = 'status',
        callback: Callable[[int], None] | None = None,
    ) -> resource.ResourceT:
        """Wait for the resource to be in a particular status.

        :param session: The session to use for making this request.
        :param resource: The resource to wait on to reach the status. The
            resource must have a status attribute specified via ``attribute``.
        :param status: Desired status of the resource.
        :param failures: Statuses that would indicate the transition
            failed such as 'ERROR'. Defaults to ['ERROR'].
        :param interval: Number of seconds to wait between checks.
        :param wait: Maximum number of seconds to wait for transition.
            Set to ``None`` to wait forever.
        :param attribute: Name of the resource attribute that contains the
            status.
        :param callback: A callback function. This will be called with a single
            value, progress. This is API specific but is generally a percentage
            value from 0-100.

        :returns: The updated resource.
        :raises: :class:`~openstack.exceptions.ResourceTimeout` if the
            transition to status failed to occur in ``wait`` seconds.
        :raises: :class:`~openstack.exceptions.ResourceFailure` if the resource
            transitioned to one of the states in ``failures``.
        :raises: :class:`~AttributeError` if the resource does not have a
            ``status`` attribute
        """
        return resource.wait_for_status(
            self, res, status, failures, interval, wait, attribute, callback
        )

    def wait_for_delete(
        self,
        res: resource.ResourceT,
        interval: int | float | None = 2,
        wait: int | None = 120,
        callback: Callable[[int], None] | None = None,
    ) -> resource.ResourceT:
        """Wait for a resource to be deleted.

        :param res: The resource to wait on to be deleted.
        :param interval: Number of seconds to wait before to consecutive
            checks.
        :param wait: Maximum number of seconds to wait before the change.
        :param callback: A callback function. This will be called with a single
            value, progress, which is a percentage value from 0-100.

        :returns: The resource is returned on success.
        :raises: :class:`~openstack.exceptions.ResourceTimeout` if transition
            to delete failed to occur in the specified seconds.
        """
        return resource.wait_for_delete(self, res, interval, wait, callback)
