#include "fileid_btree.h"

int FileIdBTree::key_equal_op(const Key* const key, const void* const data)
{
	const void* ptr = data;
	const bool has_extension = (data_at<uint8_t>(ptr, 0) & 0x2) != 0;
	ptr = advance_pointer(ptr, 1);
	const uint32_t name_index = extract_value_and_advance(&ptr);
	const uint32_t extension_index = has_extension ? extract_value_and_advance(&ptr) : 0;
	if (name_index > key->name_index)
		return -1;
	else if (name_index < key->name_index)
		return 1;
	if (extension_index > key->extension_index)
		return -1;
	else if (extension_index < key->extension_index)
		return 1;
	return 0;
}

int FileIdBTree::key_less_than_op(const Key* const key, const void* const data)
{
	const void* ptr = data;
	const uint32_t name_index = extract_value_and_advance(&ptr);
	const uint32_t extension_index = extract_value_and_advance(&ptr);
	if (name_index > key->name_index)
		return -1;
	else if (name_index < key->name_index)
		return 1;
	if (key->extension_index < extension_index)
		return -1;
	else
		return 1;
}

const void* FileIdBTree::skip_node_data(const void* const node) const
{
	const void* ptr = node;
	const uint32_t unk1 = extract_value_and_advance(&ptr);
	return ptr;
}

int FileIdBTree::traverse_callback(const void* const data, void* const arg)
{
	const TraverseCallbackArgs<TraverseFileIdCallback>* const args = static_cast<const TraverseCallbackArgs<TraverseFileIdCallback>*>(arg);

	int action = kTRAVERSE_CONTINUE;

	FileId file_id;
	if (file_id.parse(data) && args->callback)
		action = (*args->callback)(&file_id, args->arg);

	return action;
}
