/*
 * Copyright 2016 - 2022 Gary Talent (gary@drinkingtea.net). All rights reserved.
 */

#include <nfd.hpp>

#include <ox/std/error.hpp>
#include <ox/std/string.hpp>
#include <ox/std/trace.hpp>

#include "filedialog.hpp"

namespace nostalgia::studio {

static ox::Result<ox::String> toResult(nfdresult_t r, const NFD::UniquePathN &path) noexcept {
	switch (r) {
		case NFD_OKAY:
			return ox::String(path.get());
		case NFD_CANCEL:
			return OxError(1, "Operation cancelled");
		default:
			return OxError(2, NFD::GetError());
	}
}

ox::Result<ox::String> saveFile(const ox::Vector<FDFilterItem> &filters) noexcept {
	NFD::Guard guard;
	NFD::UniquePathN path;
	ox::Vector<nfdnfilteritem_t, 5> filterItems(filters.size());
	for (auto i = 0u; const auto &f : filters) {
		filterItems[i] = {f.name.c_str(), f.spec.c_str()};
		++i;
	}
	return toResult(NFD::SaveDialog(path, filterItems.data(), filterItems.size()), path);
}

ox::Result<ox::String> chooseDirectory() noexcept {
	NFD::Guard guard;
	NFD::UniquePathN path;
	return toResult(NFD::PickFolder(path), path);
}

}