package com.neuroair;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@SuppressWarnings("unused")
@Component
public class EventHandler extends TextWebSocketHandler implements WebSocketHandler {
    ObjectMapper objectMapper = new ObjectMapper();

    CommandHandler commandHandler;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        System.out.println("Socket Connected: " + session);
        commandHandler = new CommandHandler(session); // Use the session to initialize CommandHandler

        // Send command to read file list upon connection
        Command command = new Command();
        command.setMethod("readFileList");
        commandHandler.execute(command);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        session.sendMessage(new TextMessage("you to " + message.getPayload()));
        Command command = objectMapper.readValue(message.getPayload(), Command.class);
        commandHandler.execute(command);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        System.out.println("Socket Closed: [" + closeStatus.getCode() + "] " + closeStatus.getReason());
        super.afterConnectionClosed(session, closeStatus);
    }
}
