#include <common.h>

#include <string.h>

static void draw_menu(WINDOW *win, int wh, int ww, char *prompt, 
    char **options, int nopt, int highlight);

int menu_select(WINDOW *win, int wh, int ww, char *prompt, char **options, 
    int nopt)
{
  int curr_opt = 0; 
  for(;;) {
    draw_menu(win, wh, ww, prompt, options, nopt, curr_opt);
    int c = wgetch(win);
    switch(c) {
      case 'w':
        if(curr_opt == 0) curr_opt = nopt - 1;
        else curr_opt--;
        break;
      case 's':
        if(curr_opt == nopt - 1) curr_opt = 0;
        else curr_opt++;
        break;
      case '\n':
        return curr_opt;
    }
  }
}

void draw_string_center(WINDOW *win, int ww, int y, char *s)
{
  int x = ww / 2 - strlen(s) / 2;
  mvwaddstr(win, y, x, s);
}

static void draw_menu(WINDOW *win, int wh, int ww, char *prompt, 
    char **options, int nopt, int highlight)
{
  wborder(win, '|', '|', '-', '-', '+', '+', '+', '+');
  int y = wh / 2 - nopt / 2 - 2;
  wattron(win, A_BOLD);
  draw_string_center(win, ww, y, prompt);
  y += 2;
  wattroff(win, A_BOLD);
  for(int i = 0; i < nopt; ++i) {
    if(i == highlight) {
      wattron(win, A_STANDOUT);
    }
    draw_string_center(win, ww, y + i, options[i]);
    if(i == highlight) {
      wattroff(win, A_STANDOUT);
    }
  }
  wrefresh(win);
}