#include <string.h>
#include "global.h"
#include "command.h"
#include "constants.h"
#include "window.h"

extern win_ptr gwin, outwin;

struct command_node levels[] =
{
  {{"NONE"},     (char *)NONE},
  {{"PUBLIC"},   (char *)PUBLIC},
  {{"MSGS"},     (char *)MSGS},
  {{"NOTICE"},   (char *)NOTICES},
  {{"WALL"},     (char *)WALL},
  {{"WALLOP"},   (char *)WALLOP},
  {{"ACTIONS"},  (char *)ACTIONS},
  {{"DCC"},      (char *)DCC},
  {{"CRAP"},     (char *)CRAP},
  {{"ALL"},      (char *)ALL},
  {{ NULL},      (char *)NULL}
};

int lookup_level(str, normal, inverse)
  char *str;
  int *normal, *inverse;
{
  char word[80];
  int level, indx, start, plus = TRUE, spec = FALSE;
  int temp_normal, temp_inverse;

  temp_normal = *normal;
  temp_inverse = *inverse;

  while ((str) && (*str)) {
    start = 0;
    spec = FALSE;
    plus = TRUE;
    (void)grab_word(&str, ' ', word);
    if (word[0] == '-') {
      start = 1;
      plus = FALSE;
    }
    else if (word[0] == '^') {
      start = 1;
      spec = TRUE;
    }
    else if (word[0] == '+') start = 1;

    level = lookup_command(levels, &word[start], &indx);
    if (level<0) return FALSE;
    if (indx==0) {
      if (spec) temp_inverse = 0;
      else if (plus) temp_normal = 0;
    } else {
      if (spec) {
        temp_inverse = temp_inverse | indx;
        temp_normal = temp_normal & (ALL - indx);
      } else if (plus) {
        temp_normal = temp_normal | indx;
        temp_inverse = temp_inverse & (ALL - indx);
      } else {
        temp_normal = temp_normal & (ALL - indx);
        temp_inverse = temp_inverse & (ALL - indx);
      }
    }
  }
  *normal = temp_normal;
  *inverse = temp_inverse;
  return TRUE;
}

void show_level(str, norm, inverse, ret)
  int norm, inverse;
  char *str, *ret;
{
  char string[MAXLEN], *msg;
  int loop, dummy;
  win_ptr old_outwin;

  if (ret) msg = ret;
  else msg = string;
  *msg =0;
  if (norm == ALL) (void)strcpy(msg, "ALL");
  else if (norm != NONE)
    for (loop = 1; levels[loop].command; loop++) {
      dummy = (int)(levels[loop].constant);
      if ((norm & dummy) == dummy) {
        if (*msg) (void)strcat(msg, " ");
        (void)strcat(msg, levels[loop].command);
      }
    }
  if (inverse == ALL)
    (void)strcat(msg, "Don't-ALL");
  else if (inverse != NONE)
    for (loop = 1; levels[loop].command; loop++) {
      dummy = (int)(levels[loop].constant);
      if ((inverse & dummy) == dummy) {
        if (*msg) (void)strcat(msg, " ");
        (void)strcat(msg, "Don't-");
        (void)strcat(msg, levels[loop].command);
      }
    }
  if ((norm==NONE) && (inverse==NONE)) (void)strcpy(msg, "NONE");
  if (!ret) {
    old_outwin = outwin;
    outwin = gwin;
    say("*** %-15s%s", str, msg);
    outwin = old_outwin;
  }
}
