% Callback executed when the user clicks on the save button.
%
% M Hewitson
%
% $Id: cb_saveBtn.m,v 1.4 2009/09/11 18:23:37 ingo Exp $
%
function cb_saveBtn(varargin)
  
  myh = varargin{1};
  mainfig  = varargin{end};
  % Get connection
  % mainfig  = findobj('Tag', 'LTPDARepomainfig');
  conn     = mainfig.connection;
  if isempty(conn) || ~isa(conn, 'database')
    utils.helper.errorDlg('Please connect to a database first', 'No connection found');
    return
  end
  
  % Get variable name specs
  h = findobj(mainfig.handle, 'Tag', 'objPrefixTxt');
  prefix = get(h, 'String');
  if isempty(prefix)
    prefix = 'obj';
    warning('! Using default prefix (obj)');
  end
  h = findobj(mainfig.handle, 'Tag', 'appendObjTypeChk');
  appendObj = get(h, 'Value');
  h = findobj(mainfig.handle, 'Tag', 'retrieveBinaryChk');
  retrieveBinary = get(h, 'Value');
  % Get IDs from text box
  [ids, cids] = getIds(mainfig);
  
  
  %---------------------------------------------------------------
  % Retrieve these ids
  objs = [];
  for j=1:length(ids)
    disp(sprintf('+ retrieving object %d', ids(j)));
    
    % determine object type
    tt = utils.mysql.getObjType(conn, ids(j));
    objname = sprintf('%s%03d', prefix, ids(j));
    if ~isempty(tt) && ~strcmp(tt, 'No Data')
      if appendObj
        objname = [objname '_' tt];
      end
    else
      error('!!! Object type is unknown. Does this object really exist?');
    end
    % add file extension
    objname = [objname '.xml'];
    
    % Retrieve object
    a = regexp(conn.URL, '//(\S+)/', 'tokens');
    db = regexp(conn.URL, '/', 'split');
    db = db{end};
    % add history
    pl = plist('hostname', a{1}, 'database', db, 'ID', ids(j), 'conn', conn);
    if retrieveBinary
      pl.append('Binary', 'yes');
      disp(sprintf('*** performing binary retrieval.'));
    end
    obj = eval(sprintf('%s(pl);', tt));
    
    % write to disk
    save(obj, objname)
    
    %   assignin('base', objname, obj);
    disp(sprintf('** Retrieve object %d to disk [%s]', ids(j), objname));
    
    if j==1
      objs = {obj};
    else
      objs = [objs {obj}];
    end
  end
  
  disp(sprintf('** Retrieved %d objects.', length(ids)));
  
  %---------------------------------------------------------------
  % Retrieve these Collections
  for k=1:length(cids)
    
    % get Ids from Cid
    ids = mysql_getObjIds(conn, cids(k));
    if isempty(ids)
      error('### This collection doesn''t seem to exist.');
    end
    
    for j=1:length(ids)
      disp(sprintf('+ retrieving collection %d : %d', cids(k), ids(j)));
      tt = utils.mysql.getObjType(conn, ids(j));
      objname = sprintf('%sC%03d_%03d', prefix, cids(k), ids(j));
      if appendObj
        objname = [objname '_' tt];
      end
      % Retrieve object
      ipbits = regexp(conn.URL, '([0-9]+)', 'match');
      ip = [ipbits{1} '.' ipbits{2} '.' ipbits{3} '.' ipbits{4}];
      db = regexp(conn.URL, '/', 'split');
      db = db{end};
      % add history
      pl = plist('hostname', ip, 'database', db, 'ID', ids(j), 'conn', conn);
      obj = eval(sprintf('%s(pl);', tt));
      
      assignin('base', objname, obj);
      disp(sprintf('** Retrieve object %d to workspace [%s]', ids(j), objname));
      if j==1
        objs = {obj};
      else
        objs = [objs {obj}];
      end
    end
  end
  
  disp(sprintf('** Retrieved %d objects.', length(ids)));
  
  
end


function [ids, cids] = getIds(mainfig)
  
  ids  = [];
  cids = [];
  
  th = findobj(mainfig.handle, 'Tag', 'retrieveIDsTxt');
  idStr = get(th, 'String');
  cs = cellstr(idStr);
  
  for j=1:length(cs)
    disp('---------')
    ls = cs{j};
    [s,r] = strtok(ls);
    if ~isempty(s)
      if s(1) == 'c'
        s = s(2:end);
        cids = [cids round(str2num(s))];
      else
        ids = [ids round(str2num(s))];
      end
    end
    while ~isempty(r)
      [s,r] = strtok(r);
      if ~isempty(s)
        if s(1) == 'c'
          s = s(2:end);
          cids = [cids round(str2num(s))];
        else
          ids = [ids round(str2num(s))];
        end
      end
    end
  end  
end
