"""
Example: configure HDMI output and display a text overlay using the LT API client

This example demonstrates how to:
    1. Connect to an LT310 device and verify that a given input source is active.
    2. Configure an HDMI output to use that input source.
    3. Initialize a canvas and draw text on it.
    4. Set the HDMI output overlay to display the canvas.

Usage:
    hdmi_out.exe -source <inputSource> [-text <overlayText>]

Arguments:
    -source, -s    URL of a valid input on the LT device, for example:
                       hdmi-in/0
                       sdi-in/1

    -text, -t      Optional text to render on the video overlay.
                   Default: "Hello, World!"

Note:
     This code is intended for demonstration purposes. For production use,
     ensure proper error handling and resource cleanup.

© 2025 Enciris Technologies. All rights reserved.
"""

import argparse

if __package__:
    from ... import lt
else:
    import sys
    sys.path.append("../..")
    import lt


# Command line arguments
def parse_args():
    class MyParser(argparse.ArgumentParser):
        def error(self, message):
            self.print_help()
            self.exit(2, f"\nError: {message}\n")

    parser = MyParser(
        description=(
            "This example routes the selected input to HDMI output 0, creates a canvas with custom text,\n"
            "and applies the canvas as an overlay on the HDMI output."
        ),
        formatter_class=argparse.RawTextHelpFormatter,
        add_help=False
    )

    group = parser.add_argument_group("Arguments")
    group.add_argument(
        "-source", "-s",
        required=True,
        metavar="URL",
        help=(
            "URL of a valid input on the LT device (e.g. hdmi-in/0)\n"
        )
    )
    group.add_argument(
        "-text", "-t",
        required=False,
        metavar="TEXT",
        help=(
            "Optional text to render on the video overlay (default: \"Hello, World!\")\n"
        )
    )

    return parser.parse_args()

# Base path for the LT310 board : first board in the system
boardBase = "lt310:/0/"

def main():
    args = parse_args()
    sourceURL = args.source
    overlayText = args.text if args.text else "Hello, World!"

    # Create LT client
    client = lt.Client()

    try:
        # -------------------------------------------------------------------------
        # Check if input selected is active
        # -------------------------------------------------------------------------
        input = client.Get(boardBase + sourceURL)
        if input['video']['signal'] != 'locked':
            raise RuntimeError("input video source has no signal")

        # -------------------------------------------------------------------------
        # Set HDMI output source
        # -------------------------------------------------------------------------
        client.Post(boardBase + "hdmi-out/0", lt.JSON({'source': sourceURL}))

        print("hdmi-out source set to: %s" % sourceURL)

        # -------------------------------------------------------------------------
        # Get HDMI output parameters
        # -------------------------------------------------------------------------
        output = client.Get(boardBase + "hdmi-out/0")

        # -------------------------------------------------------------------------
        # Initialize the canvas with the same size as HDMI output
        # -------------------------------------------------------------------------
        client.Post("lt310:/canvas/0/init", lt.JSON({'size': output['video']['size']}))

        # -------------------------------------------------------------------------
        # Draw text on the canvas
        # -------------------------------------------------------------------------
        client.Post("lt310:/canvas/0/text", lt.JSON({
            'text': overlayText,
            'fontSize': 200,
            'color': [255, 255, 255, 255],
            'size': output['video']['size']
        }))

        # -------------------------------------------------------------------------
        # Apply the canvas as an HDMI overlay
        # -------------------------------------------------------------------------
        client.Post(boardBase + "hdmi-out/0", lt.JSON({'overlay': "canvas/0"}))

    except lt.SDKError as e:
        raise RuntimeError(f"error connecting to {boardBase + sourceURL}: {e}") from e

    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    main()
