package brn.gui.actions;

import java.io.File;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;

import brn.gui.Activator;
import brn.gui.BrnGuiConstants;
import brn.gui.commands.ICommandIds;
import brn.gui.reports.PlaceResources;
import brn.gui.reports.PreviewEditor;
import brn.gui.reports.PreviewEditorInput;

public class OpenDatabaseBrowserAction extends Action {

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

  private String reportName = "/studyOverview.rptdesign";

  private String driver = "com.mysql.jdbc.Driver";
  
  private String url = "jdbc:mysql://";

  private IWorkbenchWindow window;

  public OpenDatabaseBrowserAction(String label, IWorkbenchWindow window) {
    super();
    this.window = window;

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

    try {
      PlaceResources.copyReports( window.getShell(),
          getDefaultLocation( ));
    } catch (CoreException e) {
      Activator.log(e);
      setEnabled(false);
    }
  }

  private String getDefaultLocation( )
  {
    IPath defaultPath = Platform.getLocation( );
    return defaultPath.toOSString( );
  }

  @Override
  public void run() {
    IPreferenceStore store = Activator.getDefault().getPreferenceStore();

    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);

    File file = new File(getDefaultLocation() + reportName);
    PreviewEditorInput input = new PreviewEditorInput(file,
        driver, url+host+"/"+database, user, password);
    
    IWorkbenchPage page = window.getActivePage();
    if (page != null)
      try {
        page.openEditor(input, PreviewEditor.ID);
      } catch (PartInitException e) {
        Activator.log(e);
      }
  }

}
