# Copyright (c) 2024, D-Robotics.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration


def generate_launch_description():
    camera_launch = IncludeLaunchDescription(
        PythonLaunchDescriptionSource(
            os.path.join(
                get_package_share_directory("car_usb_cam"),
                "launch",
                "hobot_usb_cam.launch.py",
            )
        ),
        launch_arguments={
            "usb_frame_id": LaunchConfiguration("usb_frame_id"),
            "usb_framerate": LaunchConfiguration("usb_framerate"),
            "usb_image_height": LaunchConfiguration("usb_image_height"),
            "usb_image_width": LaunchConfiguration("usb_image_width"),
            "usb_io_method": LaunchConfiguration("usb_io_method"),
            "usb_pixel_format": LaunchConfiguration("usb_pixel_format"),
            "usb_video_device": LaunchConfiguration("usb_video_device"),
            "usb_zero_copy": LaunchConfiguration("usb_zero_copy"),
        }.items(),
    )

    websocket_launch = IncludeLaunchDescription(
        PythonLaunchDescriptionSource(
            os.path.join(
                get_package_share_directory("websocket"),
                "launch",
                "websocket.launch.py",
            )
        ),
        launch_arguments={
            "websocket_image_topic": "/image",
            "websocket_image_type": "mjpeg",
            "websocket_only_show_image": "True",
            "websocket_output_fps": "30",
        }.items(),
    )

    return LaunchDescription([
        DeclareLaunchArgument("usb_frame_id", default_value="default_usb_cam"),
        DeclareLaunchArgument("usb_framerate", default_value="30"),
        DeclareLaunchArgument("usb_image_height", default_value="720"),
        DeclareLaunchArgument("usb_image_width", default_value="1280"),
        DeclareLaunchArgument("usb_io_method", default_value="mmap"),
        DeclareLaunchArgument("usb_pixel_format", default_value="mjpeg"),
        DeclareLaunchArgument("usb_video_device", default_value="/dev/video0"),
        DeclareLaunchArgument("usb_zero_copy", default_value="false"),
        camera_launch,
        websocket_launch,
    ])
