package no.dusken.momus.service;

import lombok.extern.slf4j.Slf4j;
import no.dusken.momus.model.Messageable;
import no.dusken.momus.model.websocket.Action;
import no.dusken.momus.model.websocket.EntityMessage;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashMap;

@Service
@Slf4j
public class MessagingService {

    private final SimpMessagingTemplate messagingTemplate;

    public MessagingService(SimpMessagingTemplate messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    public void broadcastEntityAction(Messageable entity, Action action) {
        log.debug("Broadcasting {} and action {}", entity, action);
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        String messageId = attributes.getRequest().getHeader("X-MOM-SENDER");

        HashMap<String, Object> headers = new HashMap<>();
        headers.put("message-sender", messageId);
        entity.getDestinations().forEach(destination ->
                messagingTemplate.convertAndSend(destination, new EntityMessage(entity, action), headers)
        );
    }
}

@@ -872,205 +872,60 @@
 n);%0A
-        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();%0A        String messageId = attributes.getRequest().getHeader(%22X-MOM-SENDER%22
+%0A        String messageId = getMessageIdFromRequest(
 );%0A%0A
@@ -1195,16 +1195,16 @@
 eaders)%0A
-
         
@@ -1211,11 +1211,351 @@
 );%0A    %7D
+%0A%0A    private String getMessageIdFromRequest() %7B%0A        try %7B%0A            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();%0A            return attributes.getRequest().getHeader(%22X-MOM-SENDER%22);%0A        %7D catch(IllegalStateException e) %7B%0A            return %22%22;%0A        %7D%0A    %7D
 %0A%7D%0A

Fix bug with messaging