#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
from ament_index_python.packages import get_package_share_directory
import http.server
import socketserver
import threading
import os
import webbrowser

class ThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
    pass

class UIServerNode(Node):
    def __init__(self):
        super().__init__('ui_server_node')

        # Parameters
        self.declare_parameter('port', 8080)
        self.port = self.get_parameter('port').value

        # Locate UI directory in share space
        share_dir = get_package_share_directory('fori_serial_bridge')
        self.ui_dir = os.path.join(share_dir, 'ui')

        if not os.path.exists(self.ui_dir):
            # Fallback to source directory for development / symlink install
            self.ui_dir = os.path.expanduser('~/fori_ws/fori_ws/src/fori_serial_bridge/ui')
            if not os.path.exists(self.ui_dir):
                self.ui_dir = os.path.expanduser('~/fori_ws/src/fori_serial_bridge/ui')

        self.get_logger().info(f'Serving UI files from directory: {self.ui_dir}')

        # Start HTTP server in a separate daemon thread
        self.server_thread = threading.Thread(target=self.start_server, daemon=True)
        self.server_thread.start()

    def start_server(self):
        # Use a custom handler that serves from the UI directory without changing
        # the global working directory (which would break other ROS node operations)
        ui_dir = self.ui_dir

        class UIHandler(http.server.SimpleHTTPRequestHandler):
            def __init__(self, *args, **kwargs):
                super().__init__(*args, directory=ui_dir, **kwargs)

            def log_message(self, format, *args):
                pass  # Suppress HTTP access logs in ROS terminal output

        try:
            self.server = ThreadingHTTPServer(("", self.port), UIHandler)
            self.get_logger().info('==========================================')
            self.get_logger().info(f'     Web UI Dashboard server launched!    ')
            self.get_logger().info(f'     Connect via: http://localhost:{self.port} ')
            self.get_logger().info('==========================================')
            
            # Automatically open default web browser after 1 second delay
            def auto_open_browser():
                url = f"http://localhost:{self.port}"
                try:
                    opened = webbrowser.open(url)
                    if not opened:
                        os.system(f"xdg-open {url} >/dev/null 2>&1 &")
                except Exception:
                    os.system(f"xdg-open {url} >/dev/null 2>&1 &")

            threading.Timer(1.0, auto_open_browser).start()

            self.server.serve_forever()
        except Exception as e:
            self.get_logger().error(f'Failed to start web server on port {self.port}: {e}')

    def destroy_node(self):
        self.get_logger().info('Shutting down Web UI server...')
        if hasattr(self, 'server'):
            self.server.shutdown()
            self.server.server_close()
        super().destroy_node()

def main(args=None):
    rclpy.init(args=args)
    node = UIServerNode()
    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        pass
    finally:
        if rclpy.ok():
            node.destroy_node()
            rclpy.shutdown()

if __name__ == '__main__':
    main()
