/*
 *------------------------------------------------------------------
 *
 * $Source: /afs/net.mit.edu/dev/project/techinfodev/src/srv_ti/RCS/nlist.c,v $
 * $Revision: 3.2 $
 * $Date: 93/02/03 11:21:24 $
 * $State: Exp $
 * $Author: thorne $
 * $Locker:  $
 *
 * $Log:	nlist.c,v $
 * Revision 3.2  93/02/03  11:21:24  thorne
 * new release
 * 
 * Revision 1.3  92/08/24  15:46:45  ark
 * WAIS searching added to client & server (J command)
 * 
 * Revision 1.2  92/08/04  16:27:50  ark
 * Test production version 8/4/92
 * 
 * Revision 1.1  92/07/22  11:09:22  ark
 * Saber loads quietly; ANSI use standardized; command line options; no behavioral changes
 * 
 * Revision 1.0  92/07/10  12:32:33  ark
 * Initial revision
 * 
 * Revision 1.1  91/07/15  10:40:28  thorne
 * Initial revision
 * 
 *------------------------------------------------------------------
 */

#ifndef lint
#ifndef SABER
static char *rcsid_foo_c = "$Header: /afs/net.mit.edu/dev/project/techinfodev/src/srv_ti/RCS/nlist.c,v 3.2 93/02/03 11:21:24 thorne Exp $";
#endif SABER
#endif  lint

/*
 * nlist.c 
 *
 * Calls for building a list of nodes out of various sub structures of the node
 * web. 
 *
 * Created 7-15-89 -- SMF 
 */
/*
  Copyright (C) 1989 by the Massachusetts Institute of Technology

   Export of this software from the United States of America is assumed
   to require a specific license from the United States Government.
   It is the responsibility of any person or organization contemplating
   export to obtain such a license before exporting.

WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
distribute this software and its documentation for any purpose and
without fee is hereby granted, provided that the above copyright
notice appear in all copies and that both that copyright notice and
this permission notice appear in supporting documentation, and that
the name of M.I.T. not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.  M.I.T. makes no representations about the suitability of
this software for any purpose.  It is provided "as is" without express
or implied warranty.

  */

#include <stdio.h>
#include <sys/time.h>
#include "pdb.h"
#include "web.h"
#include "nlist.h"
#include "network.h"

extern int      SERVER;
extern int      menu;
extern int      disptype;

static NLIST	nlist[NLIST_MAX_LEN];

static int numnode;
static u_short  curdepth;

#define	width_exactly(w)	(w), (w)	/* for -*.*s fields */

NLIST *
nlist_current(void)			/* For send_nlist in transact.c */
{
	return nlist;
}

void
nlist_reset(void)
{				/* Empty out node list */
	numnode = curdepth = 0;
}

short
nlist_numnode(void)
{
	return numnode;
}

void
nlist_set_numnode(int num)
{
	numnode = num;
}

NODE *
nlist_node(int relative_id)
{
	if (relative_id >= numnode || relative_id < 0) {
		printf("Bad relative id#%d ", relative_id);
		return (NODE *) 0;
	}
	return nlist[relative_id].n;
}

short
nlist_lev(int relative_id)
{
	if (relative_id > numnode)
		return 0;
	return nlist[relative_id].lev;
}

int
nlist_find_id(long nid, int list_len)
{
	int             i;

	for (i = 0; i < list_len; i++) {
		if (n_id(nlist_node(i)) == nid)
			return i;
	}
	return -1;
}

/* switch the position of two nodes in the list */
void
nlist_swap(int pos, int pos2)
{				
	NODE           *tmpnode;
	u_short         tmp_depth;
	
	tmpnode = nlist[pos].n;
	tmp_depth = nlist[pos].lev;
	nlist[pos].n = nlist[pos2].n;
	nlist[pos].lev = nlist[pos2].lev;
	nlist[pos2].n = tmpnode;
	nlist[pos2].lev = tmp_depth;
}

void
nlist_add(NODE * n, u_short depth)
{
	if (!n) 
	  {
	    printf("Tried to add null ptr node to nlist\n");
	    return;
	  }

	/* Added check so that we don't go off end of array.
	   We let numnode increase as large as it wants, but we never
	   try to write off the end of the array .
	   7/24/92  ark */
	if (numnode < NLIST_MAX_LEN)
	  {
	    nlist[numnode].n = n;
	    nlist[numnode].lev = depth;
	  }
	
	numnode++;

	if (curdepth < depth)
	  curdepth = depth;
}



extern char *srch_topic;

void
nlist_add_srch(NODE * n, u_short depth)
{
  char *cp;
  int len;
  int nlistidx;

        len = strlen(srch_topic);
	if (!n) {
		printf("Tried to add null ptr node to nlist\n");
		return;
	      }

        for (nlistidx = 0;
	     nlistidx < numnode && nlist[nlistidx].n != n;
	     nlistidx++);

        if (numnode > 0 && nlistidx < numnode) {
	  /* Add each node to nlist ONLY ONCE!!! murphy@dccs.upenn.edu */
	  return;
	}

        cp = n_topic(n);

        do {
	  /* skip leading spaces */
	  while (*cp == ' ')
	    cp++;
	  
          if (!strncasecmp(cp, srch_topic, len)) {
	    /* Only store if in bounds (see nlist_add above) */
	    if (numnode < NLIST_MAX_LEN)
	      {
		nlist[numnode].n = n;
		nlist[numnode].lev = 0; 
	      }
	  
	    numnode++;

	    /* */ if (curdepth < depth)
	      curdepth = depth;
	    break;  /* murphy@dccs.upenn.edu - add node only once!! */
	  }
	  else if (cp = index(cp, ',')) cp++;
	} while (cp);
}

/* This function is new for WAIS searching */
void
nlist_add_srchflag(NODE * n, u_short depth)
{
  if (!n) 
    {
      printf("Tried to add null ptr node to nlist\n");
      flush();
      return;
    }
  if (flagset(n, N_HIT))
    {
      nlist[numnode].n = n;
      nlist[numnode].lev = 0; /* changed by ST 9/14/92 */
      numnode++;
      /* */ if (curdepth < depth)
	     curdepth = depth;
      clrflag(n, N_HIT);
    }
  else
    return;
}


extern int srch_yr;
extern int srch_mo;
extern int srch_day;

/* check to see if the node is newer than the date (globals) */
/* ARGSUSED */
void 
nlist_changed_since(NODE * n, u_short dummy)
{   
  time_t thetime;
  struct   tm *thedate;
  
  if (is_menu_node(n))
    return;
  
  thetime = (time_t) n_date(n)*86400;
  thedate = localtime(&thetime);
  if (thedate->tm_year > srch_yr)
    goto ADD;
  if (thedate->tm_year < srch_yr)
    return;
  if ((thedate->tm_mon+1) > srch_mo)
    goto ADD;
  if (thedate->tm_mon+1 < srch_mo) 
    return;
  if (thedate->tm_mday >= srch_day)
    goto ADD;
  if (thedate->tm_mday < srch_day)
    return;
 ADD:
  nlist_add(n,0);
  return;
}

extern char *srch_source;
void 
nlist_source_srch(NODE * n, u_short dummy)
{    /* return nodes of a given source */

  if (strncasecmp(n_source(n),srch_source,strlen(srch_source)) != 0)
    return;
else
    nlist_add(n,0);
return;
}

void
nlist_del(long nid)
{
	int             i;
	i = nlist_find_id(nid, numnode);
	nlist[i].n = nlist[numnode - 1].n;
	nlist[i].lev = nlist[numnode - 1].lev;
	numnode--;
}


void
nlist_build(int dir, NODE * n, u_short levels)
{
	/* curdepth = levels; */
	web_traverse(dir, n, nlist_add, levels);
}

void
nlist_expand(u_short levels)
{
	NLIST		*tmp_nlist, *nl;
	unsigned int    tmp_blen;
	int             i, tmp_numnode, maxlev;

	tmp_numnode = numnode;
	tmp_blen = sizeof(NLIST) * tmp_numnode;
	tmp_nlist = (NLIST *) domalloc(tmp_blen);
	bcopy(nlist, tmp_nlist, tmp_blen);
	numnode = 0;
	nl = tmp_nlist;
	if (!SERVER)
		levels = levels + curdepth;

	/*
	 * This doesn't do anything that really makes sense if we've just done
	 * a find. 
	 */

	if (nl->lev) {
		maxlev = nl->lev;
		levels = (maxlev - 1) + levels;
		for (i = 0; i < tmp_numnode; i++, nl++)
			if (nl->lev == maxlev)
				web_traverse(TRAV_DOWN, nl->n, nlist_add, levels);
	} else {
		/* levels += curdepth;  */
		for (i = 0; i < tmp_numnode; i++, nl++)
			if (!nl->lev)
				web_traverse(TRAV_DOWN, nl->n, nlist_add, levels);
	}
	free(tmp_nlist);
}



void
nlist_fio(char *file, int op, int msgs)
{
	static char     _nliobuf[BUFSIZ];

	FILE           *fp;
	char           *home, *getenv();
	char            savefile[64];
	char           *openmode;
	int             i, old_num, new_pos, pid;

	long            nid;
	u_short         nlev;
	char            buf[16];
	
	pid = getpid();
	if (!(home = getenv("HOME")))
		home = "/tmp";
	if (!file)
		sprintf(file,".pips.save.%d",pid);
	if (*file == '/')
		strncpy(savefile, file, 62);
	else
		sprintf(savefile, "%.50s/%s", home, file);

	openmode = (op == NL_SAVE ? "w+" : "r");

	if ((fp = fopen(savefile, openmode)) == 0) {
		perror(savefile);
		return;
	}
	setbuf(fp, _nliobuf);

	/*
	 * *** NL_SAVE *** 
	 */

	if (op == NL_SAVE) {
		if (msgs)
			printf("Saving current list to [%s]...", savefile), flush();
		for (i = 0; i < numnode; i++)
			fprintf(fp, "%05ld %d\n", n_id(nlist_node(i)),
				nlist_lev(i));
		fclose(fp);
		if (msgs)
			printf("%d items were saved to [%s]", --i, savefile), flush();
		return;
	}
	/*
	 * *** NL_RESTORE *** 
	 */

	if (op != NL_RESTORE && op != NL_RESTORE_OR && op != NL_RESTORE_AND) {
		printf("nlist_fio: op=?"), flush();
		return;
	}
	if (msgs)
		printf("Restoring list from [%s]...", savefile), flush();
	old_num = numnode;
	if (op == NL_RESTORE)
		nlist_reset();
	i = 0;
	while (fgets(buf, 16, fp)) {
		nid = atol(buf);
		nlev = atoi(&buf[6]);
		nlist_add(web_node(nid), nlev);
		i++;
	}
	if (msgs)
		printf("%d items being restored from [%s]...", i, savefile), flush();
	fclose(fp);
	if (msgs)
		printf("%d items were restored from [%s]", i, savefile), flush();
	if (op == NL_RESTORE_OR) {	/* do we need to eliminate repeats
					 * here */
		for (i = old_num; i < numnode; i++) {
			if (nlist_find_id(n_id(nlist[i].n), i) != -1)
				nlist_del(n_id(nlist[i].n));
		}
	}
	if (op == NL_RESTORE_AND) {
		new_pos = 0;
		for (i = old_num; i < numnode; i++) {
			if (nlist_find_id(n_id(nlist[i].n), old_num) != -1) {
				nlist[new_pos].n = nlist[i].n;
				nlist[new_pos].lev = nlist[i].lev;
				new_pos++;
			}
		}
		numnode = new_pos;
	}
}

/*****************************************************************************/
/*****************************************************************************/
/*****************************************************************************/

 /* static */ int indent_per_lev = 2;
 /* static */ int topic_fld_len = 26;
 /* static */ int title_fld_len = 31;

/*
 * This stuff prob should be reorganized somehow. It's also a nasty nasty
 * mess. 
 */

/*
static char    *
node_pretty_fmt(NODE *n, int lineno, int depth)
{
	static char     buf[1024];

	char           *fmt = "%4d  %-*.*s %-*.*s%-*.*s  %-5.5s %8.8s";
	int             indent, topic_space;
	char            nbuf[8], nid[10];
	long            secs;
	struct tm      *thedate;

	indent = indent_per_lev * depth;
	if (indent > topic_fld_len)
		indent = topic_fld_len;
	topic_space = topic_fld_len - indent;
	if (topic_space < 0)
		topic_space = 0;
	if (is_menu_node(n))
		sprintf(nbuf, "%3d S", n_numchild(n));
	else
		sprintf(nbuf, "%3d D", n_numchild(n));
	secs = (long) (n_date(n) * 86400);
	thedate = localtime(&secs);
	sprintf(nid, "%8d", n_id(n));

	sprintf(buf, fmt,
		lineno + 1,
		width_exactly(title_fld_len),
		n_title(n),
		width_exactly(indent), "| | | | | | | | | | | | | | |",
		width_exactly(topic_space),
		n_topic(n),
		nbuf,
		nid);

	return buf;
} */

static char    *
node_pretty_fmt(NODE *n, int lineno, int depth)
{


	static char     buf[1024];

	char           *fmt = "%4d  %-*.*s %-*.*s%-*.*s %-1.1s   %8.8s    %5.5s";
	int             indent, topic_space;
	char            nbuf[8], nid[10],theday[10];
	time_t            secs;
	struct tm       *thedate;

	indent = indent_per_lev * depth;
	if (indent > topic_fld_len)
		indent = topic_fld_len;
	topic_space = topic_fld_len - indent;
	if (topic_space < 0)
		topic_space = 0;
	if (flagset(n,N_IMAGE))
	  sprintf(nbuf, "I");
	else if (is_menu_node(n))
	  sprintf(nbuf, "S");
	else
	  sprintf(nbuf, "D");
	if (!is_menu_node(n))
	  {
	    secs = (time_t) (n_date(n) * 86400);
	    thedate = localtime(&secs);
	    sprintf(theday,"%2d/%2d/%2d",thedate->tm_mon +1,thedate->tm_mday, 
		    thedate->tm_year);
	  }
	else
	  sprintf(theday,"        ");
	sprintf(nid, "%5.5d", n_id(n));

	sprintf(buf, fmt,
		lineno + 1,
		width_exactly(title_fld_len),
		n_title(n),
		width_exactly(indent), "| | | | | | | | | | | | | | |",
		width_exactly(topic_space),
		n_topic(n),
		nbuf,theday,
		nid);

	return buf;
}

/* a test of a stripped down disp */
static char    *
node_pretty_fmt2(NODE *n, int lineno, int depth)	
{


	static char     buf[1024];

	char           *fmt2 = "%19d  %*.*s %-s";
	int             indent;

	indent = indent_per_lev * depth;
	sprintf(buf, fmt2,
		lineno + 1, width_exactly(indent), " | | | | | | | | | |",
		n_title(n));
	return buf;
}

char           *
nlist_fmt_line(int lineno)
{
	int             num, depth;

	if ((lineno+menu) >= nlist_numnode())
		return "";

	num = lineno;
	depth = nlist_lev(lineno);
	if (menu) {		/* Menu kludge */
		depth = 0;
		lineno++;

	}
	if (disptype == FULL)
		return node_pretty_fmt(nlist_node(lineno), num, depth);
	else
		return node_pretty_fmt2(nlist_node(lineno), num, depth);
}

/*
 * This is for dump_nlist, who needs to specify an nlist to use,
 * cause it may be a thread who's saved it.
 */

char *
nlist_fmt_line_part_two(int i, NLIST *nlist)
{
	int             num, depth;

	num = i;
	depth = nlist[i].lev;
	if (menu) {				/* Menu kludge */
		depth = 0;
		i++;
	}
	if (disptype == FULL)
		return node_pretty_fmt(nlist[i].n, num, depth);
	else
		return node_pretty_fmt2(nlist[i].n, num, depth);
}
