/*
 * Copyright © 2021-2026 Pierrick Caillon <pierrick.caillon+zipdirfs@megami.fr>
 */
#include "ZipDirFs/Fuse/NativeSymlink.h"
#include "ZipDirFs/Components/NativeChanged.h"
#include "ZipDirFs/Utilities/FileSystem.h"
#include <filesystem>
#include <memory>

namespace ZipDirFs::Fuse
{
	namespace fs = std::filesystem;

	std::map<const fs::path*, std::unique_ptr<std::string>> nativeSymlinkTargets;
	const char* NativeSymlinkInitTarget(const fs::path&);
	std::unique_ptr<std::string> NativeSymlinkOwnTarget(const fs::path&);

	NativeSymlink::NativeSymlink(const fs::path& p) :
		basic_symlink(NativeSymlinkInitTarget(p)), path(p),
		target(NativeSymlinkOwnTarget(p)), changed(path)
	{
		// ReSharper disable once CppVirtualFunctionCallInsideCtor
		changed();
	}
	std::time_t NativeSymlink::getChangeTime() const { return std::time_t{Components::NativeChanged::FileTime{changed}}; }
	std::time_t NativeSymlink::getModificationTime() const { return std::time_t{Components::NativeChanged::FileTime{changed}}; }

	const char* NativeSymlinkInitTarget(const fs::path& p)
	{
		nativeSymlinkTargets.emplace(&p, std::make_unique<std::string>(p.native()));
		return nativeSymlinkTargets[&p].get()->c_str();
	}

	std::unique_ptr<std::string> NativeSymlinkOwnTarget(const fs::path& p)
	{
		auto temp = std::move(nativeSymlinkTargets[&p]);
		nativeSymlinkTargets.erase(&p);
		return temp;
	}
} // namespace ZipDirFs::Fuse
