/*-*-c++-*-
 * $Id: strset.cpp,v 1.1 2002/01/28 15:38:33 holzheu Exp $
 *
 * This file is part of qlcrash, a GUI for the dump-analysis tool lcrash.
 *
 * Copyright (C) 2001 IBM Deutschland Entwicklung GmbH, IBM Corporation
 *
 * Authors:
 * Michael Geselbracht (let@users.sourceforge.net)
 * Fritz Elfert (elfert@de.ibm.com)
 * Michael Holzheu (holzheu@de.ibm.com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version. See the file COPYING for more
 * information.
 */
#include "strset.h"

#define MAX_SUGGESTIONS 5

StrSet::StrSet() : Avl<QString>(false), oMaxSuggestions(MAX_SUGGESTIONS)
{
}

StrSet::~StrSet()
{
}

void
StrSet::setMaxSuggestions(unsigned int n)
{
	oMaxSuggestions = n;
}

AvlList<QString>*
StrSet::getSuggestions(const QString& key)
{
	oCounter = 0;
	oList = 0;
	
	if (key.length() >= 2) {
		getSuggestions_priv(oRoot, key);
	}
	
	return oList;
}

void
StrSet::getSuggestions_priv(AvlNode<QString>* root, const QString& key)
{
	if (root == 0)
		return;
	
	const int len = key.length();
	int cmp = key.compare(root->next->key.left(len));
	
	if (cmp < 0) {
		getSuggestions_priv(root->left, key);
	}
	else if (cmp > 0) {
		getSuggestions_priv(root->right, key);
	}
	else {
		oCounter++;
		if (oCounter > oMaxSuggestions) {
			oList->dispose();
			oList = 0;
			return;
		}
		
		// add a new item in front of oList
		if (oList == 0) {
			oList = new AvlList<QString>(root->next->key);
			oList->next = 0;
		}
		else {
			AvlList<QString>* item;
			item = new AvlList<QString>(root->next->key);
			item->next = oList;
			oList = item;
		}
		
		// go on with recursion
		getSuggestions_priv(root->left, key);
		getSuggestions_priv(root->right, key);
	}
}
