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

import "doc_Storage.jnc"
import "ui_ComboBox.jnc"

namespace ui {

//! \addtogroup common-ui
//! @{

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

extension ComboBoxHistory: ComboBox {
	bool addEditTextToHistory();

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

	void removeExtraItems(size_t limit);

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

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

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

bool ComboBoxHistory.addEditTextToHistory() {
	if (!m_editText || !*m_editText)
		return false;

	addToHistory(m_editText);
	return true;
}

void 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;

			insertItem(0, text);
			removeItem(i + 1);
			removeExtraItems(limit);
			return;
		}

	insertItem(0, text);
	removeExtraItems(limit);
}

void ComboBoxHistory.removeExtraItems(size_t limit) {
	while (m_itemCount > limit)
		removeItem(limit);
}

void 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;
}

void 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 ui
