#
# Copyright (c) 2021 Nitric Technologies Pty Ltd.
#
# This file is part of Nitric Python 3 SDK.
# See https://github.com/nitrictech/python-sdk for further info.
#
# 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.
#

# Generated by the protocol buffer compiler.  DO NOT EDIT!
# sources: nitric/proto/topics/v1/topics.proto
# plugin: python-betterproto
# This file has been @generated

from dataclasses import dataclass
from datetime import timedelta
from typing import (
    TYPE_CHECKING,
    AsyncIterable,
    AsyncIterator,
    Dict,
    Iterable,
    Optional,
    Union,
)

import betterproto
import betterproto.lib.google.protobuf as betterproto_lib_google_protobuf
import grpclib
from betterproto.grpc.grpclib_server import ServiceBase


if TYPE_CHECKING:
    import grpclib.server
    from betterproto.grpc.grpclib_client import MetadataLike
    from grpclib.metadata import Deadline


@dataclass(eq=False, repr=False)
class ClientMessage(betterproto.Message):
    """
    ClientMessage is the message sent from the service to the nitric server
    """

    id: str = betterproto.string_field(1)
    """globally unique ID of the request/response pair"""

    registration_request: "RegistrationRequest" = betterproto.message_field(
        2, group="content"
    )
    """Register a subscription to a topic"""

    message_response: "MessageResponse" = betterproto.message_field(3, group="content")
    """Handle a message received from a topic"""


@dataclass(eq=False, repr=False)
class MessageRequest(betterproto.Message):
    topic_name: str = betterproto.string_field(1)
    message: "TopicMessage" = betterproto.message_field(2)
    """Message Type"""


@dataclass(eq=False, repr=False)
class MessageResponse(betterproto.Message):
    success: bool = betterproto.bool_field(1)


@dataclass(eq=False, repr=False)
class ServerMessage(betterproto.Message):
    """
    ServerMessage is the message sent from the nitric server to the service
    """

    id: str = betterproto.string_field(1)
    """globally unique ID of the request/response pair"""

    registration_response: "RegistrationResponse" = betterproto.message_field(
        2, group="content"
    )
    """Response to a topic subscription request"""

    message_request: "MessageRequest" = betterproto.message_field(3, group="content")
    """Response to a topic message request"""


@dataclass(eq=False, repr=False)
class RegistrationRequest(betterproto.Message):
    topic_name: str = betterproto.string_field(1)


@dataclass(eq=False, repr=False)
class RegistrationResponse(betterproto.Message):
    pass


@dataclass(eq=False, repr=False)
class TopicMessage(betterproto.Message):
    struct_payload: "betterproto_lib_google_protobuf.Struct" = (
        betterproto.message_field(1, group="content")
    )


@dataclass(eq=False, repr=False)
class TopicPublishRequest(betterproto.Message):
    """Request to publish a message to a topic"""

    topic_name: str = betterproto.string_field(1)
    """The name of the topic to publish the topic to"""

    message: "TopicMessage" = betterproto.message_field(2)
    """The message to be published"""

    delay: timedelta = betterproto.message_field(3)
    """An optional delay specified in seconds (minimum 10 seconds)"""


@dataclass(eq=False, repr=False)
class TopicPublishResponse(betterproto.Message):
    """Result of publishing an topic"""

    pass


class TopicsStub(betterproto.ServiceStub):
    async def publish(
        self,
        topic_publish_request: "TopicPublishRequest",
        *,
        timeout: Optional[float] = None,
        deadline: Optional["Deadline"] = None,
        metadata: Optional["MetadataLike"] = None
    ) -> "TopicPublishResponse":
        return await self._unary_unary(
            "/nitric.proto.topics.v1.Topics/Publish",
            topic_publish_request,
            TopicPublishResponse,
            timeout=timeout,
            deadline=deadline,
            metadata=metadata,
        )


class SubscriberStub(betterproto.ServiceStub):
    async def subscribe(
        self,
        client_message_iterator: Union[
            AsyncIterable["ClientMessage"], Iterable["ClientMessage"]
        ],
        *,
        timeout: Optional[float] = None,
        deadline: Optional["Deadline"] = None,
        metadata: Optional["MetadataLike"] = None
    ) -> AsyncIterator["ServerMessage"]:
        async for response in self._stream_stream(
            "/nitric.proto.topics.v1.Subscriber/Subscribe",
            client_message_iterator,
            ClientMessage,
            ServerMessage,
            timeout=timeout,
            deadline=deadline,
            metadata=metadata,
        ):
            yield response


class TopicsBase(ServiceBase):
    async def publish(
        self, topic_publish_request: "TopicPublishRequest"
    ) -> "TopicPublishResponse":
        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)

    async def __rpc_publish(
        self, stream: "grpclib.server.Stream[TopicPublishRequest, TopicPublishResponse]"
    ) -> None:
        request = await stream.recv_message()
        response = await self.publish(request)
        await stream.send_message(response)

    def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
        return {
            "/nitric.proto.topics.v1.Topics/Publish": grpclib.const.Handler(
                self.__rpc_publish,
                grpclib.const.Cardinality.UNARY_UNARY,
                TopicPublishRequest,
                TopicPublishResponse,
            ),
        }


class SubscriberBase(ServiceBase):
    async def subscribe(
        self, client_message_iterator: AsyncIterator["ClientMessage"]
    ) -> AsyncIterator["ServerMessage"]:
        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
        yield ServerMessage()

    async def __rpc_subscribe(
        self, stream: "grpclib.server.Stream[ClientMessage, ServerMessage]"
    ) -> None:
        request = stream.__aiter__()
        await self._call_rpc_handler_server_stream(
            self.subscribe,
            stream,
            request,
        )

    def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
        return {
            "/nitric.proto.topics.v1.Subscriber/Subscribe": grpclib.const.Handler(
                self.__rpc_subscribe,
                grpclib.const.Cardinality.STREAM_STREAM,
                ClientMessage,
                ServerMessage,
            ),
        }
