package brn.gui.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;

import brn.gui.commands.ICommandIds;
import brn.gui.datasource.Provider;
import brn.gui.datasource.Source;

public class UnlistenSimAction extends Action implements IPropertyChangeListener {

	private final static String IMAGE = "/icons/disconnect.gif";

	private Provider provider;

	public UnlistenSimAction(String label, Provider provider) {
		super();
		this.provider = provider;

		setText(label);
		// The id is used to refer to the action in a menu or toolbar
		setId(ICommandIds.CMD_UNLISTEN_SIM);
		// Associate the action with a pre-defined command, to allow key bindings.
		setActionDefinitionId(ICommandIds.CMD_UNLISTEN_SIM);
		setImageDescriptor(brn.gui.Activator.getImageDescriptor(IMAGE));

    setEnabled(null != provider.getDataSource()
        &&provider.getDataSource().isListening());
    provider.addPropertyChangeListener(this);
	}

  @Override
	public void run() {
    provider.getDataSource().unlisten();
    provider.releaseDataSource();
    
    new Thread() {
      public void run() {
        System.gc();
        try {
          Thread.sleep(300);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        System.gc();
      }
    }.start();
	}

	public void propertyChange(PropertyChangeEvent event) {
    if (event.getProperty().equals(Source.LISTENING)
        ||event.getProperty().equals(Source.DATASOURCE_DISPOSED)
        ||event.getProperty().equals(Source.DATASOURCE_CREATED)) {
      setEnabled(null != provider.getDataSource()
          &&provider.getDataSource().isListening());
    }
	}


}
