import asyncio
import logging
import random

import grpc
from common.proto.dbscanserving_pb2 import DetectionRequest, DetectionResponse, Sample
from common.proto.dbscanserving_pb2_grpc import DetectorStub
from common.Settings import get_log_level, get_setting

# For more channel options, please see https://grpc.io/grpc/core/group__grpc__arg__keys.html
CHANNEL_OPTIONS = [
    ("grpc.lb_policy_name", "pick_first"),
    ("grpc.enable_retries", True),
    ("grpc.keepalive_timeout_ms", 10000),
]

# based on https://github.com/grpc/grpc/blob/master/examples/python/helloworld/async_greeter_client_with_options.py


async def run(endpoint, service_id) -> None:

    async with grpc.aio.insecure_channel(
        target=endpoint, options=CHANNEL_OPTIONS
    ) as channel:
        stub = DetectorStub(channel)

        # generate data
        alien_samples = random.randint(2, 20)

        request: DetectionRequest = DetectionRequest()
        request.num_samples = 300 + alien_samples
        request.num_features = 20
        request.eps = 100.5
        request.min_samples = 5
        for _ in range(200):
            grpc_sample = Sample()
            for __ in range(20):
                grpc_sample.features.append(random.uniform(0.0, 10.0))
            request.samples.append(grpc_sample)
        for _ in range(100):
            grpc_sample = Sample()
            for __ in range(20):
                grpc_sample.features.append(random.uniform(50.0, 60.0))
            request.samples.append(grpc_sample)
        for _ in range(alien_samples):
            grpc_sample = Sample()
            for __ in range(20):
                grpc_sample.features.append(random.uniform(5000.0, 6000.0))
            request.samples.append(grpc_sample)
        # Timeout in seconds.
        # Please refer gRPC Python documents for more detail. https://grpc.io/grpc/python/grpc.html
        response: DetectionResponse = await stub.Detect(request, timeout=10)
    print("Greeter client received:", service_id)
    return service_id * 2


async def main_loop():
    host = get_setting("DBSCANSERVINGSERVICE_SERVICE_HOST")
    port = get_setting("DBSCANSERVINGSERVICE_SERVICE_PORT_GRPC")
    endpoint = "{:s}:{:s}".format(str(host), str(port))

    ret = await asyncio.gather(run(endpoint, 1), run(endpoint, 2))

    print(ret)


if __name__ == "__main__":

    logging.basicConfig()
    asyncio.run(main_loop())
