/*
 *    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 "TTFile.h"
#include "TTObjectSpec.h"

TTFile::TTFile (const char *new_file, Tt_status &status)
{
  setTTFileDefaults ();

  file = strcpy (new char [strlen (new_file) + 1], new_file);
  status = TT_OK;
}

TTFile::TTFile (const TTFile &new_file)
{
  copy (new_file);
}

TTFile &TTFile::operator= (const TTFile &new_file)
{
  if (this != &new_file) {
    destroyObject ();
    copy (new_file);
  }

  return *this;
}

void TTFile::setTTFileDefaults ()
{
  file = (char *)NULL;
}

TTFile::~TTFile ()
{
  destroyObject ();
}

char *TTFile::getFile (Tt_status &status) const
{
  status = TT_OK;
  return (file ? strcpy (tt_malloc (strlen (file) + 1), file) : (char *)NULL);
}

TTObjectSpecArray *TTFile::getObjectSpecs (Tt_status &status) const
{
  TTObjectSpecArray *array = new TTObjectSpecArray;

  status = tt_file_objects_query (file,
				  (Tt_filter_function) &TTFile::queryFilter,
				  (void *)NULL,
				  (void *)array);
  if (!array->getSize ()) {
    delete array;
    array = (TTObjectSpecArray *)NULL;
  }

  return array;
}

Tt_status TTFile::destroy ()
{
  return tt_file_destroy (file);
}

Tt_status TTFile::move (const char *new_file)
{
  Tt_status status = tt_file_move (file, new_file);
  if (status == TT_OK) {
    if (file)
      delete file;

    file = strcpy (new char [strlen (new_file) + 1], new_file);
  }

  return status;
}

Tt_status TTFile::move (const TTFile &new_file)
{
  Tt_status  status;
  char      *file_name = new_file.getFile (status);

  if (status == TT_OK) {
    status = tt_file_move (file, file_name);
    if (status == TT_OK) {
      if (file)
        delete file;

      file = file_name;
    }
  }

  if (status != TT_OK)
    delete file_name;

  return status;
}

Tt_status TTFile::copy (const char *new_file)
{
  return tt_file_copy (file, new_file);
}

Tt_status TTFile::copy (const TTFile &new_file)
{
  return tt_file_copy (file, new_file.file);
}

void TTFile::copyObject (const TTFile &new_file)
{
  setTTFileDefaults ();

  if (new_file.file)
    file = strcpy (new char [strlen (new_file.file) + 1], new_file.file);
}

void TTFile::destroyObject ()
{
  if (file)
    delete file;
}

Tt_filter_action TTFile::queryFilter (char *objid,
			              void * /* context */,
			              void *accumulator)
{
  if (objid) {
    Tt_status     status;
    TTObjectSpec *object_spec = new TTObjectSpec (objid, status);

    if (status == TT_OK) {
      ((TTObjectSpecArray *)accumulator)->addItem (object_spec);
    }
  }

  return TT_FILTER_CONTINUE;
}
