package brooklyn.event.basic;

import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import brooklyn.config.ConfigKey;
import brooklyn.entity.Entity;
import brooklyn.event.Sensor;
import brooklyn.location.Location;
import brooklyn.location.MachineLocation;
import brooklyn.location.PortRange;
import brooklyn.location.PortSupplier;
import brooklyn.location.basic.Locations;
import brooklyn.util.flags.TypeCoercions;

import com.google.common.base.Optional;
import com.google.common.collect.Iterables;

/**
 * A {@link Sensor} describing a port on a system,
 * with a {@link ConfigKey} which can be configured with a port range
 * (either a number e.g. 80, or a string e.g. "80" or "8080-8089" or even "80, 8080-8089, 8800+", or a list of these).
 * <p>
 * To convert at runtime a single port is chosen, respecting the entity.
 */
public class PortAttributeSensorAndConfigKey extends AttributeSensorAndConfigKey<PortRange,Integer> {
    private static final long serialVersionUID = 4680651022807491321L;
    
    public static final Logger LOG = LoggerFactory.getLogger(PortAttributeSensorAndConfigKey.class);

    public PortAttributeSensorAndConfigKey(String name) {
        this(name, name, null);
    }
    public PortAttributeSensorAndConfigKey(String name, String description) {
        this(name, description, null);
    }
    public PortAttributeSensorAndConfigKey(String name, String description, Object defaultValue) {
        super(PortRange.class, Integer.class, name, description, defaultValue);
    }
    public PortAttributeSensorAndConfigKey(PortAttributeSensorAndConfigKey orig, Object defaultValue) {
        super(orig, TypeCoercions.coerce(defaultValue, PortRange.class));
    }
    protected Integer convertConfigToSensor(PortRange value, Entity entity) {
        if (value==null) return null;
        Collection<? extends Location> locations = entity.getLocations();
        if (!locations.isEmpty()) {
            Optional<MachineLocation> lo = Locations.findUniqueMachineLocation(locations);
            if (lo.isPresent()) {
                Location l = lo.get();
                if (l instanceof PortSupplier) {
                    int p = ((PortSupplier)l).obtainPort(value);
                    if (p!=-1) {
                        LOG.debug(""+entity+" choosing port "+p+" for "+getName());
                        return p;
                    }
                    int rangeSize = Iterables.size(value);
                    if (rangeSize==0)
                        LOG.warn(""+entity+" no port available for "+getName()+" (empty range "+value+")");
                    else if (rangeSize==1) {
                        Integer pp = value.iterator().next();
                        if (pp>1024)
                            LOG.warn(""+entity+" port "+pp+" not available for "+getName());
                        else 
                            LOG.warn(""+entity+" port "+pp+" not available for "+getName()+" (root may be required?)");
                    } else {
                        LOG.warn(""+entity+" no port available for "+getName()+" (tried range "+value+")");
                    }
                    // definitively, no ports available
                    return null;
                }
                // ports may be available, we just can't tell from the location
                Integer v = (value.isEmpty() ? null : value.iterator().next());
                LOG.debug(""+entity+" choosing port "+v+" (unconfirmed) for "+getName());
                return v;
            } else {
                LOG.warn(""+entity+" ports not applicable, or not yet applicable, because has multiple locations "+locations+"; ignoring "+getName());       
            }
        } else {
            LOG.warn(""+entity+" ports not applicable, or not yet applicable, bacause has no locations, ignoring "+getName());
        }
        return null;
    }
    
}

@@ -52,16 +52,43 @@
 lection;
+%0Aimport java.util.Iterator;
 %0A%0Aimport
@@ -303,32 +303,86 @@
 achineLocation;%0A
+import brooklyn.location.MachineProvisioningLocation;%0A
 import brooklyn.
@@ -565,16 +565,58 @@
 tional;%0A
+import com.google.common.base.Predicates;%0A
 import c
@@ -2099,77 +2099,920 @@
 nal%3C
-MachineLocation%3E lo = Locations.findUniqueMachineLocation(locations);
+? extends Location%3E lo = Locations.findUniqueMachineLocation(locations);%0A            if (!lo.isPresent()) %7B%0A                // Try a unique location which isn't a machine provisioner%0A                Iterator%3C? extends Location%3E li = Iterables.filter(locations,%0A                        Predicates.not(Predicates.instanceOf(MachineProvisioningLocation.class))).iterator();%0A                if (li.hasNext()) lo = Optional.of(li.next());%0A                if (li.hasNext()) lo = Optional.absent();%0A            %7D%0A            // Fall back to selecting the single location%0A            if (!lo.isPresent() && locations.size() == 1) %7B%0A                lo = Optional.of(locations.iterator().next());%0A            %7D%0A            if (LOG.isTraceEnabled()) %7B%0A                LOG.trace(%22Convert config to sensor for %7B%7D found locations: %7B%7D. Selected: %7B%7D%22,%0A                        new Object%5B%5D %7Bentity, locations, lo%7D);%0A            %7D
 %0A   
@@ -3838,17 +3838,16 @@
     else
- 
 %0A       
@@ -4514,32 +4514,32 @@
        %7D else %7B%0A
+
                 
@@ -4672,23 +4672,16 @@
 Name());
-       
 %0A       

Make behaviour of PortAttributeSensorAndConfigKey.convertConfigToSensor backwards compatible