/*
 *      menu.c from Access Point SNMP Utils for Linux
 *
 * Copyright (c) 2002 Roman Festchook <roma at polesye dot net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 from
 * June 1991 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

#include <stdlib.h>
#include <unistd.h>
#include <menu.h>
#include "ap-utils.h"

extern WINDOW *sub_for_menu;
extern char set_oeminfo_allowed;

void uni_menu(struct umitems *umenu, int num)
{
    ITEM **menu_item = calloc(num+1, sizeof(ITEM));
    MENU *menu;
    unsigned short int idx;
    int c;

    for (idx = 0; idx < num; idx++) {
	menu_item[idx] = new_item(umenu[idx].item, 0);
    }
    menu = new_menu(menu_item);

    set_menu_opts(menu, O_ONEVALUE);

    curs_set(0);

    post_menu(menu);

    print_help(umenu[0].help);

    while (1) {
	wrefresh(sub_for_menu);
	switch (getch()) {
	case KEY_DOWN:
	case 'j':
	case 'J':
	    menu_driver(menu, REQ_NEXT_ITEM);
	    break;
	case KEY_RIGHT:
	case 'l':
	case 'L':
	    menu_driver(menu, REQ_LAST_ITEM);
	    break;
	case KEY_LEFT:
	case 'h':
	case 'H':
	    menu_driver(menu, REQ_FIRST_ITEM);
	    break;
	case KEY_UP:
	case 'k':
	case 'K':    
	    menu_driver(menu, REQ_PREV_ITEM);
	    break;
	case KEY_PPAGE:
	case KEY_HOME:
	    menu_driver(menu, REQ_FIRST_ITEM);
	    break;
	case KEY_NPAGE:
	case KEY_END:
	    menu_driver(menu, REQ_LAST_ITEM);
	    break;
	case 'q':
	case 'Q':
	    idx = num - 2;
	    goto quitmenu;
	case 's':
	case 'S':
	    if (set_oeminfo_allowed) {
		set_menu_mark(menu, " ");
		set_menu_fore(menu, A_NORMAL);
		wrefresh(sub_for_menu);
		atmel_set_oeminfo();
		set_menu_mark(menu, "-");
		set_menu_fore(menu, A_STANDOUT);
	    }
	    break;
	/* Enter */
	case 10:
	    idx = item_index(current_item(menu));
quitmenu:
	    if (idx == num - 2) {
		unpost_menu(menu);
		free_menu(menu);
		for (c = 0; c < num; c++)
		    free_item(menu_item[c]);
		if (umenu[idx].func) 
		    umenu[idx].func();
		else {
		    free(menu_item);
		    return;
		}
	    }
	    if (umenu[idx].is_menu)
		unpost_menu(menu);

	    umenu[idx].func();

	    if (umenu[idx].is_menu)
		post_menu(menu);

	    break;
	default:
	    continue;    	
	}    
	print_help(umenu[item_index(current_item(menu))].help);
    }
}
