package brn.gui.actions;

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

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

public class ListenSimAction extends Action implements IPropertyChangeListener {

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

  private Provider provider;

  public ListenSimAction(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_LISTEN_SIM);
    // Associate the action with a pre-defined command, to allow key bindings.
    setActionDefinitionId(ICommandIds.CMD_LISTEN_SIM);
    setImageDescriptor(brn.gui.Activator.getImageDescriptor(IMAGE));

    setEnabled(null == provider.getDataSource()
        ||provider.getDataSource().isListenPossible());
    provider.addPropertyChangeListener(this);
  }

  @Override
  public void run() {
    IPreferenceStore store = Activator.getDefault().getPreferenceStore();
    String dataSource = store.getString(BrnGuiConstants.PREF_DATA_SOURCE);

    if (dataSource.equals(BrnGuiConstants.PREF_DATA_SOURCE_DB)) {
      String host = store.getString(BrnGuiConstants.PREF_DB_HOST);
      String database = store.getString(BrnGuiConstants.PREF_DATABASE);
      String user = store.getString(BrnGuiConstants.PREF_DB_USER);
      String password = store.getString(BrnGuiConstants.PREF_DB_PASSWORD);
      int jobId = store.getInt(BrnGuiConstants.PREF_DB_JOBID);

      provider.createDatabaseSource(host, database, user, password, jobId);
    } else {
      provider.createSimulationSource();
    }

    if (null != provider.getDataSource())
      provider.getDataSource().listen();
  }

  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().isListenPossible());
    }
  }

}
