package leigh.meteros;

import leigh.eo.EO;
import leigh.esp.sdk.ESPClient;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;
import leigh.mecha.util.UniversalJob;
import leigh.teremetori.sdk.producer.TelemetrySource;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * MeterosApp implements an OS monitoring daemon based on the Teremetori service.
 *
 * @author Alex Leigh
 */
public class MeterosApp implements Runnable {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(MeterosApp.class);
    private final TelemetrySource esp;
    private final String publishUri = "/test/meteros";

    public static void main(String args[]) {
        UniversalJob.banner(logger, "Meteros");
        new MeterosApp().run();
    }

    public MeterosApp() {
        esp = new TelemetrySource(new ESPClient("https://leigh-co.com"), publishUri);
    }

    @Override
    public void run() {
        while(true) {
            EO currentValues = new EO();
            try {
                currentValues.setValue("leigh.meteros.os.ip", InetAddress.getLocalHost().getHostAddress());
                currentValues.setValue("leigh.meteros.os.hostname", InetAddress.getLocalHost().getHostName());
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }

            Runtime rt = Runtime.getRuntime();
            currentValues.setValue("leigh.meteros.os.cpu.available", rt.availableProcessors());

            logger.info("Publishing update. [update: {}}", currentValues);

            esp.update(new EO().setValue("channel", "meteros"), currentValues, null);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
