package de.tum.in.www1.artemis.web.websocket;

import static de.tum.in.www1.artemis.config.websocket.WebsocketConfiguration.IP_ADDRESS;

import java.security.Principal;
import java.time.Instant;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import de.tum.in.www1.artemis.web.websocket.dto.ActivityDTO;

@Controller
public class ActivityService implements ApplicationListener<SessionDisconnectEvent> {

    private static final Logger log = LoggerFactory.getLogger(ActivityService.class);

    private final SimpMessageSendingOperations messagingTemplate;

    public ActivityService(SimpMessageSendingOperations messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    @SubscribeMapping("/topic/activity")
    @SendTo("/topic/tracker")
    public ActivityDTO sendActivity(@Payload ActivityDTO activityDTO, StompHeaderAccessor stompHeaderAccessor, Principal principal) {
        activityDTO.setUserLogin(principal.getName());
        activityDTO.setSessionId(stompHeaderAccessor.getSessionId());
        activityDTO.setIpAddress(stompHeaderAccessor.getSessionAttributes().get(IP_ADDRESS).toString());
        activityDTO.setTime(Instant.now());
        log.debug("Sending user tracking data {}", activityDTO);
        return activityDTO;
    }

    @Override
    public void onApplicationEvent(SessionDisconnectEvent event) {
        ActivityDTO activityDTO = new ActivityDTO();
        activityDTO.setSessionId(event.getSessionId());
        activityDTO.setPage("logout");
        messagingTemplate.convertAndSend("/topic/tracker", activityDTO);
    }
}

@@ -358,23 +358,30 @@
 otation.
-Payload
+MessageMapping
 ;%0Aimport
@@ -430,22 +430,23 @@
 otation.
-SendTo
+Payload
 ;%0Aimport
@@ -515,79 +515,8 @@
 ns;%0A
-import org.springframework.messaging.simp.annotation.SubscribeMapping;%0A
 impo
@@ -1163,16 +1163,14 @@
    @
-Subscrib
+Messag
 eMap
@@ -1201,56 +1201,19 @@
     
-@SendTo(%22/topic/tracker%22)%0A    public ActivityDTO
+public void
  sen
@@ -1671,14 +1671,58 @@
     
-return
+messagingTemplate.convertAndSend(%22/topic/tracker%22,
  act
@@ -1729,16 +1729,17 @@
 ivityDTO
+)
 ;%0A    %7D%0A
@@ -1921,32 +1921,32 @@
 etSessionId());%0A
-
         activity
@@ -1968,16 +1968,73 @@
 gout%22);%0A
+        log.debug(%22Session disconnect %7B%7D%22, activityDTO);%0A
         

fix user tracker