package lc.esp.service.clock;

import lc.esp.sdk.ESPClient;
import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;
import lc.mecha.util.BasicallyDangerous;

import javax.jms.*;
import java.time.Instant;

/**
 * This is a trivial implementation of an ESP service which provides the current time. This is primarily useful
 * for dev/test.
 *
 * @author Alex Leigh
 * @since mk17 (GIPSY DANGER)
 */
public class ClockService extends BasicallyDangerous {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(ClockService.class);
    private final ESPClient esp = new ESPClient();

    public static void main(String[] args) {
        new ClockService().run();
    }

    @Override
    public void runDangerously() throws Exception {
        // Unfortunately, ActiveMQ does not support AutoCloseable
        Connection connection = esp.getConnectionFactory().createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic("CLOCK");
        MessageProducer producer = session.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        //noinspection InfiniteLoopStatement
        while (true) {
            TextMessage msg = session.createTextMessage(Instant.now().toString());
            producer.send(msg);
            Thread.sleep(500);
        }
    }
}
