% CB_GET_DBS callback when the user clicks the 'get dbs' button.
%
% M Hewitson 22-09-08
%
% $Id: cb_get_dbs.m,v 1.2 2011/04/08 08:56:36 hewitson Exp $
%

function cb_get_dbs(varargin)

  % Handles
  myh     = varargin{1};
  mainfig = varargin{end};

  tables = {'collections', 'objmeta', 'objs', 'transactions', 'users'};

  % Get conn
  conn = mainfig.connection;
  % Assume I don't need to open the connection
  wasEmpty = 0;

  % Open connection, if necessary
  if isempty(conn)

    % we opened the connection
    wasEmpty = 1;

    % have we a stored username and password
    dbuser = mainfig.dbuser;
    dbpass = mainfig.dbpass;

    % get hostname
    hostname = get(findobj(mainfig.handle, 'Tag','RepoguiServerEdit'), 'String');
    if isempty(hostname)
      error('### Please select a server to connect to.');
    end

    % connect
    if ~isempty(dbuser) && ~isempty(dbpass)
      conn = utils.mysql.connect(hostname, 'test', dbuser, dbpass);
    else
      [conn, dbpass] = utils.mysql.connect(hostname);
    end
    if ~isa(conn, 'database')
      error('### couldn''t connect to server');
    end

    % store the connection
    mainfig.dbuser = conn.Username;
    mainfig.dbpass = dbpass;

  end

  % get the databases
  q = 'show databases';
  curs = exec(conn, q);
  curs = fetch(curs);

  ltpda_dbs = [];
  % Now get the LTPDA databases
  for j=1:length(curs.Data)
    db = curs.Data{j};

    if ~strcmp(db, 'information_schema')

      q = sprintf('show tables from %s', db);
      c = exec(conn, q);
      c = fetch(c);
      match = 0;
      for l=1:length(c.Data)
        for k=1:length(tables)
          if strcmp(c.Data{l}, tables{k})
            match = match + 1;
          end
        end
      end
      close(c);
      if match == 5
        % we have an LTPDA database
        ltpda_dbs = [ltpda_dbs cellstr(db)];
      end
    end

  end
  close(curs);

  % If I opened the connection, close it again
  if wasEmpty
    close(conn);
  end

  % Set the list
  id = findobj(mainfig.handle, 'Tag', 'RepoguiDatabaseList');
  set(id, 'String', ltpda_dbs, 'Value', 1);

  % Get selected DB
  dbh = findobj(mainfig.handle, 'Tag', 'RepoguiDatabaseList');
  dbs = get(dbh, 'String');
  db  = dbs{1};

  % set selected DB
  dbh = findobj(mainfig.handle, 'Tag', 'RepoguiDatabaseEdit');
  set(dbh, 'String', db);

end
