"""
Thin wrapper for requesting TCP latency metrics
"""
from importlib import import_module
import os
import pkgutil

from preseem import PreseemGrpcClient
from ._apiutil import load_api, op, op_sync
import preseem_protobuf.metrics


class PreseemMetrics:
    """API to Preseem Metrics."""

    def __init__(self, client: PreseemGrpcClient) -> None:
        """Initialize with a GRPC client."""
        self._client = client
        self.cache_enabled = False
        self._objs = {}
        self._types = {}

    def _load(self, wrapper):
        pkgpath = os.path.dirname(preseem_protobuf.metrics.__file__)
        for x in pkgutil.iter_modules([pkgpath]):
            if x.name.endswith('_pb2_grpc'):
                name = x.name[:-9]  # trim "_pb2_grpc" from the name
                # Load the python modules for this model object type
                pmod = import_module(f'preseem_protobuf.metrics.{name}_pb2')
                gmod = import_module(f'preseem_protobuf.metrics.{name}_pb2_grpc')
                load_api(self, wrapper, pmod, gmod)

    async def init(self):
        """Dynamically load TCP latency protobuf modules."""
        await self._client.connect()
        self._load(op)

    def load(self):
        """Dynamically load TCP latency protobuf modules. (non-asyncio)"""
        self._client._connect()
        self._load(op_sync)
