/*-------------------------------------------------------------------------
 *
 * tgPrint.c--
 *    
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
 *    /usr/local/devel/pglite/cvs/src/bin/psql/tgPrint.c,v 1.2 1995/04/28 22:28:59 jolly Exp
 *
 *-------------------------------------------------------------------------
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tdb.h"
#include "tgPrint.h"

int tgPrint_wrapAround = 0; /* default is not to wrap around */

typedef struct _tgprintrec {
  int size;
  int *length;
  int *currPos;
} TgPrintRec;

static void TgPrintTuple(TgTuple *, TgPrintRec *);

void 
TgPrintAttHeader(TgTupleGroup *g)
/*
 * TgPrintAttHeader -- print the attribute header for a TgTupleGroup.
 */
{
  int i;

  fprintf(stdout, "\n");
  TgPrintRowSeparator(g->numAttributes);
  
  for (i = 0 ; i < g->numAttributes ; i++) {
    fprintf(stdout, "| %-15.15s ", g->attribute[i].name);
  }
  fprintf(stdout, "|\n");
  TgPrintRowSeparator(g->numAttributes);
}

void 
TgPrintRowSeparator(int num)
/*
 * TgPrintRowSeparator -- print a +----+----... --+ separator.
 */
{
  int i;

  for (i = 0 ; i < num ; i++) {
    fprintf(stdout, "+-----------------");
  }
  fprintf(stdout, "+\n");
}

void 
TgPrintTuples(TgTupleGroup *g)
/*
 * PrintTuples -- print tuples.
 */
{
  int i;
  TgPrintRec r;

  r.size = g->numAttributes;
  r.length = (int *) malloc (sizeof(int) * r.size);
  r.currPos = (int *) malloc (sizeof(int) * r.size);
  
  for (i = 0 ; i < g->numTuples ; i++) {
    TgPrintTuple(g->tuple+i, &r);
    TgPrintRowSeparator(g->numAttributes);
  }
  TG_FREE(free, r.length);
  TG_FREE(free, r.currPos);
}


void 
TgPrintTuple(TgTuple *t, TgPrintRec *r)
{
  int i;
  int more;

  for (i = 0 ; i < r->size ; i++) {
    r->length[i] = ((*t)[i] == NULL) ? 0 : strlen((*t)[i]);
    r->currPos[i] = 0;
  }
  
  if (tgPrint_wrapAround)
    {
      /* wrap around printing */
      do {
	more = 0;
	for (i = 0 ; i < r->size ; i++) {
	  if (r->currPos[i] >= r->length[i]) {
	    fprintf(stdout, "|                 ");
	  } else {

	    fprintf(stdout, "| %-15.15s ", ((char *) (*t)[i]) + r->currPos[i]);
	    r->currPos[i] += 15;
	    if (r->currPos[i] < r->length[i]) {
	      more++;
	    }
	
	  }
	}
	fprintf(stdout, "|\n");
      } while (more);
    }
  else 
    { /* print each attribute w/o wrap around */
      for (i=0;i<r->size;i++) {
	if (r->length[i] == 0)
	  fprintf(stdout, "%-15.15s","");
	else
	  if (r->length[i] < 15)
	    fprintf(stdout, "| %-15s ", ((char *) (*t)[i]));
	  else
	    fprintf(stdout, "| %s ", ((char *) (*t)[i]));
      }
      fprintf(stdout, "|\n");
    }
}

void 
TgPrintTupleGroup(TgTupleGroup *g)
/*
 * TgPrintTupleGroup -- print things in a table format
 */
{
  fprintf(stdout, "\n");
  if (g == NULL) {
    fprintf(stdout, "TgTupleGroup is (NULL)\n");
    return;
  }
  TgPrintAttHeader(g);
  TgPrintTuples(g);
  fprintf(stdout, "\n");
}
