import grpc
import sys
import logging

from .utils import get_creds
from .config import ENV_CONFIG
from .grpc_options import COMMON_CHANNEL_OPTIONS
from yandex.cloud.priv.resourcemanager.v1 import folder_service_pb2, folder_service_pb2_grpc

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)  # FIXME
logger = logging.getLogger(__name__)


def get_folder_list(cloud_id, token, request_id, timeout=100.0):
    # TODO page_size and next
    channel = grpc.secure_channel(
        f"{ENV_CONFIG.RESOURCE_MANAGER_HOST}:{ENV_CONFIG.RESOURCE_MANAGER_PORT}",
        get_creds(ENV_CONFIG.RESOURCE_MANAGER_HOST, ENV_CONFIG.RESOURCE_MANAGER_PORT, token),
        options=COMMON_CHANNEL_OPTIONS,
    )
    stub = folder_service_pb2_grpc.FolderServiceStub(channel)
    request = folder_service_pb2.ListFolderRequest(cloud_id=cloud_id)
    response = stub.List(request, timeout, metadata=[('x-request-id', request_id)])
    logger.debug(f"Get folder list for cloud {cloud_id} status: {response}")
    return response
