package ganglia.terracotta;

import ganglia.gmetric.GMetricSlope;
import ganglia.gmetric.GMetricType;
import ganglia.gmetric.GangliaException;

import java.io.File;
import java.io.IOException;

public class CommandLinePublisher implements Publisher {

    private static final String GMETRIC_PATH = "/usr/bin/gmetric";
    private boolean debug = false;

    public CommandLinePublisher() {
        checkGmetric();
    }
    
    public void setDebug(boolean debug) {
        this.debug = debug;
    }

    @Override
    public void publish(String processName, String attributeName, String value, GMetricType type, GMetricSlope slope, String units) throws GangliaException {
        if (debug) System.out.println(attributeName + ": " + value + " " + units);
        Runtime runtime = Runtime.getRuntime();
        String[] args = new String[5];
        args[0] = GMETRIC_PATH;
        args[1] = "--name=" + attributeName;
        args[2] = "--value=" + value;
        args[3] = "--type=" + type.getGangliaType();
        args[4] = "--units=" + units;
        try {
            Process process = runtime.exec(args);
            process.waitFor();
            process.destroy();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
        }
    }

    private void checkGmetric() {
        if (!new File(GMETRIC_PATH).exists()) {
            throw new AssertionError("Missing required executable: " + GMETRIC_PATH);
        }
    }

}
