# include "pcontrol.h"

int PrintJobStack (int Nstack);
int PrintHostStack (int Nstack);

int status (int argc, char **argv) {

  PrintJobStack (PCONTROL_JOB_ALLJOBS);
  PrintHostStack (PCONTROL_HOST_ALLHOSTS);

  return (TRUE);
}

int PrintJobStack (int Nstack) {

  int i, j, Nobject;
  Stack *stack;
  Job *job;
  struct timeval now;
  float dtime;

  stack = GetJobStack (Nstack);
  ASSERT (stack != NULL, "programming error");

  LockStack (stack);
  Nobject = stack[0].Nobject;
  gprint (GP_LOG, "job stack %s:  %d objects\n", GetJobStackName(Nstack), Nobject);

  for (i = 0; i < Nobject; i++) {
    job = stack[0].object[i];
    ASSERT (job != NULL, "programming error");
    if (job[0].realhost == NULL) {
	gprint (GP_LOG, "%3d %9s ", i, job[0].hostname);
    } else {
	gprint (GP_LOG, "%3d %9s ", i, job[0].realhost);
    }
    gprint (GP_LOG, "%7s  ", GetJobStackName (job[0].state));

    switch (job[0].state) {
	// for active jobs or pending jobs, print time since start (or create in the case of pending)
      case PCONTROL_JOB_PENDING:
      case PCONTROL_JOB_BUSY:
      case PCONTROL_JOB_RESP:
      case PCONTROL_JOB_HUNG:
	gettimeofday (&now, (void *) NULL);
	dtime = DTIME (now, job[0].start);
	gprint (GP_LOG, "%8.2f ", dtime);
	break;

	// for active jobs or pending jobs, print time since start (or create in the case of pending)
      case PCONTROL_JOB_DONE:
      case PCONTROL_JOB_KILL:
      case PCONTROL_JOB_EXIT:
      case PCONTROL_JOB_CRASH:
      default:
	dtime = DTIME (job[0].stop, job[0].start);
	gprint (GP_LOG, "%8.2f ", dtime);
	break;
    }

    PrintID (GP_LOG, job[0].JobID);
    gprint (GP_LOG, " %2d ", job[0].priority);
    for (j = 0; j < job[0].argc; j++) {
      gprint (GP_LOG, "%s ", job[0].argv[j]);
    }
    gprint (GP_LOG, "\n");
  }
  UnlockStack (stack);

  return (TRUE);
}

int PrintHostStack (int Nstack) {

  int i, Nobject;
  Stack *stack;
  Host *host;

  stack = GetHostStack (Nstack);

  LockStack (stack);
  Nobject = stack[0].Nobject;
  gprint (GP_LOG, "host stack %s:  %d objects\n", GetHostStackName(Nstack), Nobject);

  for (i = 0; i < Nobject; i++) {
    host = stack[0].object[i];
    gprint (GP_LOG, "%d  %s  ", i, host[0].hostname);
    gprint (GP_LOG, "%5s  ", GetHostStackName (host[0].stack));
    PrintID (GP_LOG, host[0].HostID);
    gprint (GP_LOG, "\n");
  }
  UnlockStack (stack);

  return (TRUE);
}

// Safe with PTHREAD_MUTEX_INITIALIZER lock
