% ADDHISTORY Add a history-object to the ltpda_uo object.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DESCRIPTION: Add a history-object to the ltpda_uoh object.
%
% CALL:        obj = addHistory(obj, minfo, h_pl, var_name, inhists, ...);
%              obj = addHistory(obj, minfo, h_pl, var_name, ismodifier, inhists, ...);
%
% VERSION:     $Id: addHistory.m,v 1.32 2011/08/16 05:16:04 hewitson Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function varargout = addHistory(varargin)

  persistent lastProcTime;
  
  
  % The object to add history to
  obj = varargin{1};

  %%% Decide on a deep copy or a modify
  obj = copy(obj, nargout);
  
  % Copy the history plist because we may modify it below
  if isa(varargin{3}, 'plist')
    pl = copy(varargin{3},1);
  else
    pl = varargin{3};
  end

  %%% Add history to all objects
  for ii = 1:numel(obj)
    if ~isempty(pl)
      % 1. replace ltpda_uoh in pl with their history
      % 2. empty the description field of a parameter ('desc')
      % 3. remove the options
      N = pl.nparams;
      for jj=1:N
        p = pl.params(jj);
        if isa(p.getVal, 'ltpda_uoh')
          p.setVal([p.getVal.hist]);
        else
          p.setVal(p.getVal);
        end
        p.setDesc('');
      end
    end
    % Remove Password from the history-plist
    if isa(pl, 'plist') && pl.isparam('password')
      pl = pl.remove('password');
    end
    % Remove Username from the history-plist
    if isa(pl, 'plist') && pl.isparam('username')
      pl = pl.remove('username');
    end
    % Remove the 'sets' and the corresponding 'plists' from the minfo
    % object. They are not important for the history step.
    varargin{2}.clearSets();
    
    % handle processing time
    t0 = time();
    proctime = t0.utc_epoch_milli;
    
    if isempty(lastProcTime)
      lastProcTime = proctime;
    else
      if proctime == lastProcTime
        proctime = proctime+1;
      end
      lastProcTime = proctime;
    end
    
    % set UUID
    uuid = char(java.util.UUID.randomUUID);
    obj(ii).UUID = uuid;
    
    h = history(proctime, varargin{2}, pl, varargin{4}, uuid, varargin{5:end});
    h.setObjectClass(class(obj(ii)));
    obj(ii).setHist(h);
    
  end

  %%% Prepare output
  varargout{1} = obj;
end
