# Copyright 2025 Leuze electronic GmbH + Co. KG
#
# Licensed under the Apache License, Version 2.0

import os
import sys

from ament_index_python.packages import get_package_share_directory
from launch.actions import TimerAction
from launch import LaunchDescription
from launch_ros.actions import Node

def generate_launch_description():
    config_file_path = os.path.join(
        get_package_share_directory('leuze_bringup')
    )

    try:

        arg4 = sys.argv[4].split(':=')
        arg5 = sys.argv[5].split(':=')
        arg6 = sys.argv[6].split(':=')
        arg7 = sys.argv[7].split(':=')

        if arg4[0] == 'ip_addr':
            ip_addr = arg4[1]

        if arg5[0] == 'port_num':
            port_num = arg5[1]

        if arg6[0] == 'topic_id':
            topic_id = arg6[1]

        if arg7[0] == 'frame_id':
            frame_id = arg7[1]

    except Exception:

        ip_addr = "192.168.60.101"      # 192.168.60.101   = default ROD x08 IP address
        port_num = "3050"               # 3050             = default ROD x08 port
        topic_id = "scan1"              # scan1            = default topic name for vizualisation script
        frame_id = "scanner_laser"      # scanner_laser    = default topic name for vizualisation script

        print("Too few arguments => Setting ip, port and topic_id to default values")

    print("Executing Leuze RODxxx driver (IP address and port =", ip_addr, ":", port_num, ", topic ID =", topic_id, ", frame ID =", frame_id, ")")

    leuze_rod_driver = Node(
        package='leuze_rod_driver',
        executable='leuze_rod_driver',
        output='screen',
        arguments=[ip_addr, port_num, topic_id, frame_id]
    )

    launch_actions = []

    return LaunchDescription([
        TimerAction(
            period=1.0,
            actions=launch_actions
        ),

        leuze_rod_driver,
    ])