package brn.gui.datasource;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.util.IPropertyChangeListener;

import brn.gui.Activator;
import brn.gui.datasource.actions.ProviderAction;

public class Provider {

  private Source dataSource;

  private ProviderAction action;

  public Provider() {
    action = new ProviderAction();
  }

  public void createSimulationSource() {
    releaseDataSource();

    dataSource = new SimulatorSource(action);
  }

  public void createDatabaseSource(String host, String database,
      String user, String password, int jobId) {
    releaseDataSource();

    DatabaseSource dbSource = new DatabaseSource(action);
    try {
      dbSource.connect(host, database, user, password, jobId);
    } catch (CoreException e) {
      // TODO show message
      Activator.log(e);
      return;
    }

    dataSource = dbSource;
    action.dataSourceCreated(dataSource);
  }

  /**
   * @return the dataSource
   */
  public Source getDataSource() {
    return dataSource;
  }

  public void addPropertyChangeListener(IPropertyChangeListener listener) {
    action.addPropertyChangeListener(listener);
  }

  public void removePropertyChangeListener(IPropertyChangeListener listener) {
    action.removePropertyChangeListener(listener);
  }

  public void releaseDataSource() {
    if (null != dataSource) {
      Source source = dataSource;
      dataSource = null;

      action.dataSourceDisposed(source);
      source.dispose();
    }
  }

}
