/*
 * Copyright © 2021-2026 Pierrick Caillon <pierrick.caillon+zipdirfs@megami.fr>
 */
#include "ZipDirFs/Components/ChangedStart.h"

namespace ZipDirFs::Components
{
	ChangedStart::ChangedStart(std::function<FileTime()>&& firstValue,
		std::function<std::unique_ptr<Changed>()>&& buildReal,
		std::shared_ptr<ChangedProxy>& target) :
		called(false), firstValue(std::move(firstValue)), buildReal(std::move(buildReal)),
		target(target)
	{
	}

	bool ChangedStart::operator()()
	{
		std::unique_ptr newChanged(buildReal());
		bool const result = (*newChanged)();
		target->swap(newChanged);
		return result;
	}

	ChangedStart::operator FileTime() const
	{
		if (!called)
		{
			*const_cast<FileTime*>(&lastChanged) = firstValue();
			*const_cast<bool*>(&called) = true;
		}
		return lastChanged;
	}
} // namespace ZipDirFs::Components
