% CB_BUILDMODEL build the tree model
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
% $Id: cb_buildModel.m,v 1.5 2010/01/29 09:31:47 hewitson Exp $
%
function cb_buildModel(varargin)
  
  wb = getappdata(0, 'WorkspaceBrowser');
  
  buildModel(wb.hdl);
  

  
end


function buildModel(wb) 
  
  %% Build workspace
  ws = mpipeline.workspace.Workspace();
  
  wvars = evalin('base', 'whos');
  
  for ll=1:numel(wvars)
    
    wvar = wvars(ll);
    
    % get the variable
    cmd = sprintf('obj = evalin(''base'', ''%s'');', wvar.name);
    eval(cmd);
    
    % user object classes
    if isa(obj, 'ltpda_uoh')
      ws = addVar(ws, obj, wvar.name);
    end
    
    if isstruct(obj)
      Nobj = numel(obj);
      for kk=1:Nobj
        if Nobj > 1
          ws = addStruct(ws, obj(kk), [wvar.name '(' num2str(kk) ')']);
        else
          ws = addStruct(ws, obj, wvar.name);
        end
      end
    end
    
  end
  
  %% make and setmodel
  
  mdl = mpipeline.workspace.WorkspaceTreeModel(ws);
  
  wb.getWorkspaceTree.setModel(mdl);
  
end

function ws = addStruct(ws, ss, name)
  
  if ~shouldAddStruct(ss)
    return
  end
  
  % make a new struct
  wsstruct = mpipeline.workspace.WorkspaceStruct(name);
  
  % add each field
  fields = fieldnames(ss);
  
  for kk=1:numel(fields)
    field = fields{kk};
    objs = ss.(field);
    if ~isnumeric(objs)
      for ll=1:numel(objs)
        if isa(objs(ll), 'ltpda_uoh')
          wsstruct = addVar(wsstruct, ss.(field), field);
        end
        
        if isstruct(objs(ll))
          wsstruct = addStruct(wsstruct, ss.(field), field);
        end
      end
    end
  end
  
  % add struct
  ws.addStruct(wsstruct);
  
end

function res = shouldAddStruct(s)
  sfields = fieldnames(s);
  res = false;
  for pp=1:numel(sfields)
    sfield = sfields{pp};
    sobj = s.(sfield);
    if isstruct(sobj) || isa(sobj, 'ltpda_uoh')      
      res = true;
      break;
    end
    if ~ischar(sobj) && ~isnumeric(sobj) && ~islogical(sobj) && numel(sobj)>1
      res = true;
      break;
    end
  end

end

function ws = addVar(ws, obj, name)
  
  % make a new var
  wsvar = mpipeline.workspace.WorkspaceVar(name, class(obj));
  
  dtxt = display(obj);
  info = '';
  for kk=1:numel(dtxt)
    info = [info [dtxt{kk} '<br>']];
  end
  
  wsvar.setInfo(info);
  % add to the workspace/workspacestruct
  ws.addVar(wsvar);
  
end

