% CB_CONNECT callback when the user clicks connect button.
%
% M Hewitson 22-09-08
%
% $Id: cb_connect.m,v 1.6 2011/04/08 08:56:26 hewitson Exp $
%

function cb_connect(varargin)

  myh     = varargin{1};
  mainfig = varargin{end};
  status  = findobj(mainfig.handle, 'Tag', 'RepoguiStatusTxt');
  panels  = mainfig.panels;

  % Get conn
  conn = mainfig.connection;

  if isempty(conn)

    % get hostname
    hostname = get(findobj(mainfig.handle, 'Tag','RepoguiServerEdit'), 'String');

    % get the database
    db = get(findobj(mainfig.handle, 'Tag','RepoguiDatabaseEdit'), 'String');

    if isempty(hostname)
      set(status,'String','Impossible to connect: please select a server first','ForeGroundcolor','r');
      error('### Please select a server first.');
    elseif isempty(db)
      set(status,'String','Impossible to connect: please select a database first','ForeGroundcolor','r');
      error('### Please select a database first.');
    end
    
    % check for username and password
    dbuser = mainfig.dbuser;
    dbpass = mainfig.dbpass;
    
    % verify if the server is reachable
    try
      java.net.InetAddress.getByName(hostname);
    catch
      set(status,'String','Impossible to connect: server not responding or no internet connection available','ForeGroundcolor','r');
      error('### Please check internet connection and server availability.');
    end

    % connect
    try
       if ~isempty(dbpass) && ~isempty(dbuser)
          conn = utils.mysql.connect(hostname, db, dbuser, dbpass, true);
       else
          [conn, dbpass] = utils.mysql.connect(hostname, db, true);
       end
    catch
        set(status,'String','Impossible to connect: please check the provided username and password','ForeGroundcolor','r');
        error('### Please check the provided username and password')
    end
      
    
    if ~ischar(conn) && ~ischar(dbpass)
      if conn==-1 && dbpass==-1
        % user cancelled
        return;
      end
    end
    
    if isa(conn, 'database')
      mainfig.connection = conn;
      mainfig.username   = conn.Username;
      set(myh, 'String', 'disconnect');
      set(status, 'String', sprintf('connected to %s on %s as %s', db, hostname, conn.Username),'ForeGroundcolor','b');

      % Set tables on query panel
      buildConditions(mainfig);

      % store the connection
      mainfig.dbuser = conn.Username;
      mainfig.dbpass = dbpass;
    else
      set(status, 'String', 'not connected','ForeGroundcolor','r');
      error('Invalid connection.');
    end
  else
    % disconnect
    close(conn);
    conn = [];
    disp('* disconnected.');
    mainfig.connection = conn;
    mainfig.username   = '';
    set(myh, 'String', 'connect');
    set(status, 'String', 'not connected','ForeGroundcolor','r');
    mainfig.dbuser = '';
    mainfig.dbpass = '';
  end

end
