# Copyright (c) 2021, NVIDIA CORPORATION.  All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto.  Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#

import omni.ext
from .service_discovery import ServiceDiscovery

g_singleton = None
# Search Service is register name, it actually service name is NGSearch in server side 
# See the start up in omni.kit.search.service
REGISTERED_NAME_TO_SERVCIE = {
    'Search Service': 'NGSearch',
}


class NucleusInfoExtension(omni.ext.IExt):
    def __init__(self):
        super().__init__()
        self._discovery = None

    def on_startup(self, ext_id):
        self._discovery = ServiceDiscovery()
        # Save away this instance as singleton
        global g_singleton
        g_singleton = self

    def on_shutdown(self):
        if self._discovery:
            self._discovery.destory()
        global g_singleton
        g_singleton = None

    def is_service_available(self, service: str, nucleus_url: str):
        if not self._discovery:
            return False

        if service in REGISTERED_NAME_TO_SERVCIE:
            return self._discovery.is_service_supported_for_nucleus(nucleus_url, REGISTERED_NAME_TO_SERVCIE[service])
        else:
            return self._discovery.is_service_supported_for_nucleus(nucleus_url, service)

    def get_nucleus_services(self, nucleus_url: str):
        if not self._discovery:
            return None
        return self._discovery.get_nucleus_services(nucleus_url)

    async def get_nucleus_services_async(self, nucleus_url: str):
        if not self._discovery:
            return None
        return await self._discovery.get_nucleus_services_async(nucleus_url)


def get_instance():
    return g_singleton