package net.hyperic.hq.product.fabric;

import java.io.IOException;
import java.util.Properties;

import net.hyperic.hq.product.MeasurementPlugin;
import net.hyperic.hq.product.Metric;
import net.hyperic.hq.product.MetricNotFoundException;
import net.hyperic.hq.product.MetricUnreachableException;
import net.hyperic.hq.product.MetricValue;
import net.hyperic.hq.product.PluginException;

public class FabricMeasurementPlugin
    extends MeasurementPlugin {

    static final String PROP_HOST    = "server.host";
    static final String PROP_PORT    = "server.port";

    public MetricValue getValue(Metric metric)
        throws PluginException,
               MetricNotFoundException,
               MetricUnreachableException 
    {
        MetricValue res;

        Properties props = metric.getProperties();
        String host = props.getProperty(FabricMeasurementPlugin.PROP_HOST);
        String port = props.getProperty(FabricMeasurementPlugin.PROP_PORT);

        props = metric.getObjectProperties();

        String component = props.getProperty("Component");
        String attr = metric.getAttributeName();

        FabricClient client = new FabricClient(host, port);

        try {
            client.connect();
        } catch (IOException e) {
            throw new MetricUnreachableException(e.getMessage(), e);
        }

        try {
            int value = client.getMetric(component, attr);
            if (value < 0) {
                throw new MetricNotFoundException(attr);
            }
            return new MetricValue(value);
        } catch (IOException e) {
            throw new MetricUnreachableException(e.getMessage(), e);
        } finally {
            try {
                client.disconnect();
            } catch (IOException e) { }
        }
    }
}
