/*  
 *    SCCS ID: %Z%%M% %I% %E% SST
 *
 *    Copyright (c) 1992-1993 Mark Soloway.  All rights reserved.
 *    See SST_LEGAL_NOTICE file for terms of the license. 
 */  
  
#include <string.h>

#include "TreeManager_consts.h"
#include "TreeNode_consts.h"
#include "TreeManager_server.h"
#include "TreeNode_server.h"
#include "TTC.h"

Tt_status TreeManager_server::defaultSessionCallback (TTMessage *message)
{
  Tt_status  status;
  char      *op = message->getOp (status);

  if (message->getStatus (status) == TT_WRN_START_MESSAGE) {
    if (status == TT_OK) {
      status = joinFile (message->getFile (status));
    }
  }

  if (status == TT_OK) {
    if (!strcmp (op, TREE_MANAGER_OP_GET_ROOT)) {
      status = getRoot (message);
    }
    else if (!strcmp (op, TREE_NODE_OP_ADD_CHILD) ||
	     !strcmp (op, TREE_NODE_OP_DELETE_NODE)) {
      TreeNode_server node (message->getObject (status), message, status);
    }
  }

  if (status < TT_WRN_LAST) {
    (void)replyToMessage (*message);
  }
  else {
    (void)failMessage (*message, status);
  }

  return status;
}

Tt_status TreeManager_server::getRoot (TTMessage *message)
{
  Tt_status  status;
  char      *file = message->getFile (status);
  
  if (status == TT_OK) {
    TTFile             tt_file (file, status);
    TTObjectSpecArray *array = tt_file.getObjectSpecs (status);
    char              *objid = (char *)NULL;
    
    if (array && (array->getSize () > 0)) {
      if (status < TT_WRN_LAST) {
        objid = ((*array) [0])->getID (status);
      }
    }
    else {
      TTObjectSpec new_root (tt_file, TREE_NODE_OTYPE, status);
      (void)new_root.setProperty (TREE_NODE_IMAGE_FILE_PROPERTY,
				  TREE_MANAGER_ROOT_IMAGE_FILE);
      status = new_root.setProperty (TREE_NODE_TEXT_PROPERTY, "Root");
      
      if (status == TT_OK) {
	status = new_root.write ();
	
	if (status == TT_OK) {
	  objid = new_root.getID (status);
	}
      }
    }
    
    if (objid && (status < TT_WRN_LAST)) {
      status = message->setArgValue (0, objid);
      delete objid;
    }

    if (array) delete array;
  }
  
  return status;
}
