/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2012 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.smartclient.internal;

import org.ow2.jonas.endpoint.collector.Endpoint;
import org.ow2.jonas.endpoint.collector.IEndpoint;
import org.ow2.jonas.endpoint.collector.IEndpointBuilder;
import org.ow2.jonas.endpoint.collector.util.Util;
import org.ow2.jonas.jmx.JmxService;
import javax.management.ObjectName;
import java.lang.String;
import java.util.regex.Pattern;

/**
 * Smartclient {@code IEndpointBuilder} implementation
 */
public class SmartclientEndpointBuilder implements IEndpointBuilder {

    /**
     * The {@link JmxService}
     */
    private JmxService jmxService;

    /**
     * The protocol
     */
    public static final String PROTOCOL = "smartclient";

    /**
     * {@inheritDoc}
     */
    public boolean isSupport(ObjectName objectName) {
        String token = this.jmxService.getDomainName() + ":type=service,name=smartclient";
        Pattern pattern = Pattern.compile(token);
        return  pattern.matcher(objectName.toString()).matches();
    }

    /**
     * {@inheritDoc}
     */
    public IEndpoint buildEndpoint(ObjectName objectName) {
        IEndpoint endpoint = new Endpoint();

        Object value = Util.getMBeanAttributeValue(objectName, "Port", this.jmxService.getJmxServer());
        if (value != null) {
            endpoint.setPort(String.valueOf(value));
        }
        endpoint.setProtocol(PROTOCOL);
        endpoint.setHost("localhost");
        endpoint.setSource(IEndpoint.SOURCE_PREFIX + PROTOCOL);
        return endpoint;
    }

    /**
     * @param jmxService The {@link JmxService} to bind
     */
    public void bindJmxService(final JmxService jmxService) {
        this.jmxService = jmxService;
    }

    /**
     * @param jmxService The {@link JmxService} to unbind
     */
    public void unbindJmxService(final JmxService jmxService) {
        this.jmxService = null;
    }
}
