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

#include <nfd.hpp>

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

#include <studio/filedialog.hpp>

namespace studio {

FDFilterItem::FDFilterItem(ox::CRStringView pName, ox::CRStringView pSpec) noexcept {
	name.resize(pName.len() + 1);
	ox_strncpy(name.data(), pName.data(), pName.len());
	spec.resize(pSpec.len() + 1);
	ox_strncpy(spec.data(), pSpec.data(), pSpec.len());
}

static ox::Result<ox::String> toResult(nfdresult_t r, NFD::UniquePathN const&path) noexcept {
	switch (r) {
		case NFD_OKAY: {
			ox::String out;
			for (auto i = 0u; path.get()[i]; ++i) {
				auto const c = static_cast<char>(path.get()[i]);
				oxIgnoreError(out.append(&c, 1));
			}
			return out;
		}
		case NFD_CANCEL:
			return OxError(1, "Operation cancelled");
		default:
			return OxError(2, NFD::GetError());
	}
}

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

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

}
