package com.bbva.arq.devops.ae.mirrorgate.api;

import com.bbva.arq.devops.ae.mirrorgate.connection.handler.ConnectionHandler;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@RestController
public class ServerSentEventsController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServerSentEventsController.class);

    private ConnectionHandler handler;


    @Autowired
    public ServerSentEventsController(ConnectionHandler handler){

        this.handler = handler;
    }

    @GetMapping(value = "/emitter/{dashboardId}")
    public SseEmitter serverSideEmitter(@PathVariable String dashboardId) throws IOException {

        LOGGER.info("Creating SseEmitter for dashboard {}", dashboardId);

        SseEmitter sseEmitter = new SseEmitter();

        sseEmitter.onCompletion(() -> {
            handler.removeFromSessionsMap(sseEmitter, dashboardId);
            sseEmitter.complete();
        });

        sseEmitter.onTimeout(() -> {
            handler.removeFromSessionsMap(sseEmitter, dashboardId);
            sseEmitter.complete();
        });

        handler.addToSessionsMap(sseEmitter, dashboardId);

        sseEmitter.send(SseEmitter.event().reconnectTime(0L));

        return sseEmitter;

    }
}

@@ -268,16 +268,75 @@
 owired;%0A
+import org.springframework.http.server.ServerHttpResponse;%0A
 import o
@@ -386,16 +386,16 @@
 apping;%0A
-
 import o
@@ -784,16 +784,386 @@
 ndler;%0A%0A
+    private static class NotCachedSseEmitter extends SseEmitter %7B%0A        @Override%0A        protected void extendResponse(ServerHttpResponse outputMessage) %7B%0A            outputMessage.getHeaders().add(%22X-Accel-Buffering%22, %22no%22);%0A            outputMessage.getHeaders().add(%22Cache-Control%22, %22no-cache;%22);%0A%0A            super.extendResponse(outputMessage);%0A        %7D%0A    %7D%0A%0A
 %0A    @Au
@@ -1489,32 +1489,32 @@
  dashboardId);%0A%0A
-
         SseEmitt
@@ -1533,16 +1533,25 @@
 r = new 
+NotCached
 SseEmitt

improve SSE performance