#include "conf-update.h"

char **find_updates(char *searchdir) {
	int max = 2;
	char **listing = (char **)malloc(sizeof(char *) * max);
	listing[0] = LAST_ENTRY;
	listing[1] = NULL;
	
	char *searchstr = strdup(searchdir);
	char *srchstrbak = searchstr;
	char *searchtok;
	
	while ((searchtok = strsep(&searchstr, " "))) {
		listing = get_files_list(searchtok, listing, &max);
	}
	free(srchstrbak);
	return listing;
}

MENU *create_menu(char **protected) {
	int i, arraycount = 0;
	ITEM **item_array;
	MENU *mymenu;
	
	for (i=0;!is_last_entry(protected[i]);i++) {
		arraycount++;
	}
	qsort(protected, arraycount, sizeof(char *), compare_updates);
	struct node *folded_protected = fold_updates(protected);
	item_array = (ITEM **)calloc(count_array_items(folded_protected) + 1, sizeof(ITEM *));
	build_item_array(item_array, folded_protected, COLS - 10);
	
	mymenu = new_menu(item_array);
	set_menu_mark(mymenu, " * ");
	menu_opts_off(mymenu, O_ONEVALUE);
	menu_opts_off(mymenu, O_NONCYCLIC);
	set_menu_fore(mymenu, A_NORMAL);
	set_menu_grey(mymenu, A_STANDOUT);
	set_menu_back(mymenu, A_STANDOUT);
	
	free_folded(folded_protected);
	set_menu_format(mymenu, LINES - 7 - 6, 1);
	return mymenu;
}

void remove_menu(MENU *mymenu) {
	ITEM **item_list = menu_items(mymenu);
	int i, cnt;
	
	unpost_menu(mymenu);
	
	// Docs say: first free menu, then free items and only then the item list, not in any other order
	cnt = item_count(mymenu);
	free_menu(mymenu);
	for (i=0;i<cnt;i++) {
		free((char *)item_name(item_list[i]));
		free_item(item_list[i]);
	}
	free(item_list);
}
