# Copyright (c) 2018-2020, 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.
#
from datetime import datetime

import omni.ext
import omni.kit.app
import omni.ui as ui
from omni.ui import color as cl

NEUTRAL = cl("#FFFFFF")
SUCCESS = cl("#3794ff")
FAILURE = cl("#CC0000")


class ExtStatusBar:
    def __init__(self):
        self._label = ui.Label("", height=8)

        app = omni.kit.app.get_app()
        bus = app.get_message_bus_event_stream()
        self._subs = []

        self._set_status("")

        def sub(e, message, color):
            self._subs.append(bus.create_subscription_to_pop_by_type(e, lambda e: self._set_status(message, color, e)))

        sub(omni.ext.EVENT_REGISTRY_REFRESH_BEGIN, "Syncing Registry...", NEUTRAL)
        sub(
            omni.ext.EVENT_REGISTRY_REFRESH_END_SUCCESS,
            "Registry Synced: " + datetime.now().strftime("%H:%M:%S"),
            SUCCESS,
        )
        sub(omni.ext.EVENT_REGISTRY_REFRESH_END_FAILURE, "Registry Sync Failed.", FAILURE)
        sub(omni.ext.EVENT_EXTENSION_PULL_BEGIN, "Installing: {}...", NEUTRAL)
        sub(omni.ext.EVENT_EXTENSION_PULL_END_SUCCESS, "Installed successfully: {}", SUCCESS)
        sub(omni.ext.EVENT_EXTENSION_PULL_END_FAILURE, "Install failed: {}", FAILURE)

    def _set_status(self, status, color=NEUTRAL, evt=None):
        if evt and evt.payload["packageId"]:
            status = status.format(evt.payload["packageId"])
        self._status = status
        self._status_color = color
        self._refresh_ui()

    def _refresh_ui(self):
        self._label.style = {"font_size": 14, "color": self._status_color}
        self._label.text = self._status
