# Copyright (c) 2022, 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.graph.core as og

# Set True to enable verbose debugging prints to console
DEBUG_PRINT = False


# ==============================================================================================================


class OgnCountdown:
    @staticmethod
    def initialize(_, node):
        og.Controller.attribute("state:count", node).set(-1)

    @staticmethod
    def compute(db) -> bool:
        def print_state(state_string: str):
            print(f"{db.node.get_prim_path()} {state_string}")

        count = db.state.count
        duration = db.inputs.duration
        count += 1
        tick_value = 1
        alpha = 0
        if count == 0:
            if DEBUG_PRINT:
                print_state("START")
            finished, tick = og.ExecutionAttributeState.LATENT_PUSH, og.ExecutionAttributeState.DISABLED
        else:
            if duration < count:
                # Finished
                finished, tick = og.ExecutionAttributeState.LATENT_FINISH, og.ExecutionAttributeState.DISABLED
                tick_value = count - 1
                alpha = 1.0
                count = -1
                if DEBUG_PRINT:
                    print_state("FINISHED")
            else:
                # Still ticking
                finished = og.ExecutionAttributeState.DISABLED
                tick_value = count
                alpha = count / max(duration, 1)
                period = db.inputs.period
                if (period == 0) or ((count % db.inputs.period) == 0):  # noqa: S001
                    tick = og.ExecutionAttributeState.ENABLED
                else:
                    tick = og.ExecutionAttributeState.DISABLED
                if DEBUG_PRINT:
                    print_state("TICK")

        # Write outputs
        db.outputs.finished = finished
        db.outputs.tick = tick
        db.state.count = count
        db.outputs.alpha = alpha
        db.outputs.tickValue = tick_value

        return True
