//..............................................................................
//
// History implementation helpers
//

import "doc_Storage.jnc"
import "gui_Base.jnc"

namespace gui {

//..............................................................................

extension ComboBoxHistory: ComboBox
{
	addEditTextToHistory ();

	addToHistory (
		char const* text,
		size_t limit = 10
		);

	saveHistory (
		doc.Storage* storage,
		char const* directory
		);

	loadHistory (
		doc.Storage* storage,
		char const* directory
		);
}

// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ComboBoxHistory.addEditTextToHistory ()
{
	return addToHistory (m_editText);
}

ComboBoxHistory.addToHistory (
	char const* text,
	size_t limit
	)
{
	for (size_t i = 0; i < m_itemCount; i++)
	{
		if (strcmp (text, m_itemText [i]) == 0)
		{
			if (!i)
				return;

			removeItem (i);
			break;
		}
	}

	insertItem (0, text);

	while (m_itemCount > limit)
		removeItem (limit);
}

ComboBoxHistory.saveHistory (
	doc.Storage* storage,
	char const* directory
	)
{
	char const* prevDirectory = storage.m_directory;

nestedscope:
	storage.m_directory = directory;

	storage.writeInt ("count", m_itemCount);

	for (size_t i = 0; i < m_itemCount; i++)
		storage.writeString ($"item$i", m_itemText [i]);

finally:
	storage.m_directory = prevDirectory;
}

ComboBoxHistory.loadHistory (
	doc.Storage* storage,
	char const* directory
	)
{
	char const* prevDirectory = storage.m_directory;

nestedscope:
	storage.m_directory = directory;

	clear ();

	size_t count = storage.readInt ("count");
	for (size_t i = 0; i < count; i++)
		addItem (storage.readString ($"item$i"));

finally:
	storage.m_directory = prevDirectory;
}

//..............................................................................

} // namespace gui {
