% Execute the query built on the query panel
%
% M Hewitson
%
% $Id: cb_executeQuery.m,v 1.7 2011/04/08 08:56:26 hewitson Exp $
%
function cb_executeQuery(varargin)

  
  % Get connection
  mainfig  = varargin{end};
  conn     = mainfig.connection;
  if isempty(conn)
    error('### Please connect to a database first.');
  end
    
  if ischar(varargin{end-1})
      q = varargin{end-1};
      fields = 'id';
      
  else
      % Get Selected fields
      fieldList = findobj(mainfig.handle, 'Tag', 'fieldsList');
      fieldsStr = get(fieldList, 'String');
      vals      = get(fieldList, 'Value');
      fields    = fieldsStr(vals)';
      
      % Get query
      h = findobj(mainfig.handle, 'Tag', 'queryDisplayTxt');
      q = get(h, 'String');
  end
  
  try
    curs = exec(conn, q);
    curs = fetch(curs);
    results = curs.Data;
    close(curs)
  catch
    warning('!!! Unable to execute query %s', q)
%     warning('!!! Server returned: %s', curs.Message);
    results = {};
    close(conn);
    conn = [];
    disp('* disconnected.');
    mainfig.connection = conn;
    mainfig.username   = '';
    set(findobj('Tag', 'ConnectButton'), 'String', 'connect');
    set(findobj(mainfig.handle, 'Tag', 'RepoguiStatusTxt'), 'String', 'not connected');
    mainfig.dbuser = '';
    mainfig.dbpass = '';
    popup2change = [findobj(mainfig.handle, 'Tag', 'tableSelect'), findobj(mainfig.handle, 'Tag', 'fieldsList'), findobj(mainfig.handle,'-regexp','Tag','.*Field$')];
    set(popup2change,'Value',1,'String',{'-'})
    set(findobj(mainfig.handle, 'Tag', 'tableSelect'),'Value', 1)
    assignin('base','prova',mainfig)
    
    error('### Unable to execute query');
  end
  
  status  = findobj(mainfig.handle, 'Tag', 'RepoguiStatusTxt');
  if ~isempty(results)
    if strcmp(results{1}, 'No Data')
      utils.helper.errorDlg('Query returned no results.', 'Query Empty');
      set(status, 'String', ['*** No results to query: ' q], 'ForeGroundcolor','r');
      return
    else
      set(status, 'String', sprintf('*** Query returned %d results', numel(results)), 'ForeGroundcolor','b');
      repogui.sqlResultsGUI(results, fields, q);
    end
  end
  
end
