package nl.nikhef.sfp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import nl.nikhef.tools.ListenerManager;

public abstract class SFPProviderBase implements SFPProvider {

	private ListenerManager<SFPProviderListener> _splMgr = 
			new ListenerManager<SFPProviderListener>(SFPProviderListener.class);
	private List<SFPDevice> _devices = new ArrayList<SFPDevice>();
	private Set<SFPDevice> _updSet = new HashSet<SFPDevice>();
	private List<SFPDevice> _umDevices = Collections.unmodifiableList(_devices);
	
	@Override
	public void addSFPDeviceListener(SFPProviderListener l) 
	{
		_splMgr.addListener(l);
	}

	@Override
	public void removeSFPDeviceListener(SFPProviderListener l) {
		_splMgr.removeListener(l);
	}
	
	protected void updAdd(SFPDevice dev) {
		_updSet.add(dev);
	}
	
	protected void updProcess() 
	{
		for (SFPDevice dev : _updSet) 
		{
			if (!_devices.contains(dev)) addDevice(dev);
		}
		
		Iterator<SFPDevice> it = _devices.iterator(); 
		
		while (it.hasNext()) {
			SFPDevice dev = it.next();
			if (!_updSet.contains(dev)) {
				it.remove();
				dev.shutdown();
				_splMgr.getProxy().sfpDeviceRemoved(this, dev);
			}
		}
		_updSet.clear();
	}
	
	protected void addDevice(SFPDevice dev)
	{
		
		_devices.add(dev);
		_splMgr.getProxy().sfpDeviceAdded(this, dev);

	}

	protected void removeDevice(SFPDevice dev)
	{
		_devices.remove(dev);
		dev.shutdown();
		_splMgr.getProxy().sfpDeviceRemoved(this, dev);
	}
	

	@Override
	public List<SFPDevice> getDevices() {
		return _umDevices;
	}
	
	@Override
	public String toString() {
		return getName();
	}

	@Override
	public void updateDevices() {
		for (SFPDevice dev : getDevices()) {
			dev.updateModules();
		}
	}
	
}
