package lc.esp.telemetry.monitor;

import lc.esp.sdk.ESPClient;
import lc.mecha.json.JSONArray;
import lc.mecha.json.JSONObject;
import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;

import javax.jms.*;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Enumeration;

public class TelemetryMonitor {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(TelemetryMonitor.class);

    public static void main(String[] args) throws JMSException {
        ESPClient esp = new ESPClient();
        Connection connection = esp.getConnectionFactory().createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // TODO: Move to constants
        Destination destination = session.createTopic("LC.TELEMETRY");
        MessageConsumer consumer = session.createConsumer(destination);
        connection.start();

        //noinspection InfiniteLoopStatement
        while (true) {
            Message msg = consumer.receive();
            JSONObject json = new JSONObject();
            if (msg instanceof TextMessage) {
                Enumeration<String> props = msg.getPropertyNames();
                for (String prop : Collections.list(props)) {
                    switch (prop) {
                        case "_time":
                            json.put(prop, new BigDecimal(msg.getDoubleProperty(prop)).toPlainString());
                            break;
                        default:
                            json.put(prop, msg.getStringProperty(prop));
                    }
                }
                json.put("symbols", new JSONArray(((TextMessage) msg).getText()));
                System.out.println(json);
            }
        }
    }
}
