% basic_newConnection basic method which creates a new connection.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% description: basic_newConnection basic method which creates a new
%              connection.
%
% version:     $Id: basic_newConnection.m,v 1.6 2010/08/16 18:04:36 ingo Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function varargout = basic_newConnection(rm, dbhost, dbname, dbuser, dbpass)
  
  % Build a new connection
  conn = mpipeline.repository.RepositoryConnection([]);
  conn.setUsername(dbuser);
  conn.setPassword(dbpass);
  conn.setDatabase(dbname);
  conn.setHostname(dbhost);
  
  % Don't show the GUI if the connection have all information
  if  ~isempty(dbhost) && ...
      ~isempty(dbname) && ...
      ~isempty(dbuser)
    if ~isempty(char(conn.getPassword))
      conn.openConnection();
    end
  else
    % Open connection GUI
    prefs = getappdata(0, 'LTPDApreferences');
    hosts = prefs.getRepoPrefs.getHostnames;
    
    % Build connection dialog
    warning('off', 'MATLAB:JavaEDTAutoDelegation');
    rcd = mpipeline.repository.RepositoryConnectionDialog([], true, hosts, conn);
    rcd.setVisible(true);
    warning('on', 'MATLAB:JavaEDTAutoDelegation');
    
    conn = rcd.getRepositoryConnection;
    
    if rcd.isCancelled
      disp('operation cancelled');
      conn = [];
    else
      if ~isempty(char(conn.getPassword))
        conn.openConnection();
      end
    end
    
  end
  
  % Add valid connection to the Repository Manager
  if isa(conn, 'mpipeline.repository.RepositoryConnection')
    rm.manager.addConnection(conn);
    if ~isempty(rm.gui)
      rm.gui.reloadConnectionTable();
    end
  else
    conn = [];
  end
  
  varargout{1} = conn;
  
end


