package com.avaya.oceanalytics.openinterface.websocketclient.subscription;

import com.avaya.oceanalytics.openinterface.websocketclient.websocket.RealtimeDataProviderException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.TimerTask;

public class HeartbeatGenerator extends TimerTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(HeartbeatGenerator.class);

    public static final String HEARTBEAT = "--heartbeat--";
    private WebSocketSession session;

    public void setSession(WebSocketSession session){
        this.session = session;
    }

    @Override
    public void run() {
        if (session == null) {
            throw new RealtimeDataProviderException("Websocket is not connected. Cannot send heartbeat to WebSocket.");
        }
        try {
            synchronized (session) {
                LOGGER.info("Sending heartbeat to WebSocket");
                session.sendMessage(new TextMessage(HEARTBEAT));
            }
        } catch (IOException e) {
            throw new RealtimeDataProviderException("Unable to send heartbeat to WebSocket", e);
        }
    }
}
