using UnityEngine;
using Unity.Robotics.ROSTCPConnector;
using RosMessageTypes.Std;

public class ROSRobotLightServer : MonoBehaviour
{
    [SerializeField] private string serviceName = "/unity/trigger_event";
    [SerializeField] public RobotLightOperation[] lightList;

    private string status = "OFF";

    void Start()
    {
        // Implement the service handler inside Unity
        ROSConnection.GetOrCreateInstance().ImplementService<TriggerRequest, TriggerResponse>(serviceName, HandleTriggerRequest);
    }

    private TriggerResponse HandleTriggerRequest(TriggerRequest request)
    {
        // Perform your Unity-side logic here (e.g., reset simulation state)
        bool wasSuccessful = TryExecuteUnityAction(); 
        string responseMessage = wasSuccessful ? $"Headlights switched {status} successfully" : "Failed to run Unity light switch action";

        // Construct and return the response
        return new TriggerResponse
        {
            success = wasSuccessful,
            message = responseMessage
        };
    }

    private bool TryExecuteUnityAction()
    {
        foreach (var item in lightList)
            item.light.intensity = item.light.intensity > .0f ? .0f : item.maxInensity;
        status = lightList[0].light.intensity  > .0f ? "ON" : "OFF";
        return true; 
    }
}

