#include "fsCloudSaveServiceLocalFolder.h"
#include <fsCore/src/fsSavedFile.h>
#include <fstream>
#include <iterator>
#include <system_error>
void fsCloudSaveServiceLocalFolder::initialize(const fsCloudSaveConfig& config)
{
if (!config.providerName.empty())
{
mProviderName = config.providerName;
}
mFolder = std::filesystem::u8path(config.localFolderPath);
std::error_code error;
std::filesystem::create_directories(mFolder, error);
}
const std::string& fsCloudSaveServiceLocalFolder::providerNameGet() const
{
return mProviderName;
}
bool fsCloudSaveServiceLocalFolder::availableGet() const
{
std::error_code error;
return !mFolder.empty() && std::filesystem::is_directory(mFolder, error);
}
void fsCloudSaveServiceLocalFolder::read(const std::string& name, ReadCallback done)
{
const std::filesystem::path path = mFolder / std::filesystem::u8path(name);
mPending.push_back([path, done]()
{
std::ifstream file(path, std::ios::binary);
if (!file)
{
done(fsCloudSaveResult::eNOT_FOUND, std::string());
return;
}
const std::string data{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
done(fsCloudSaveResult::eOK, data);
});
}
void fsCloudSaveServiceLocalFolder::write(const std::string& name, const std::string& data, DoneCallback done)
{
const std::filesystem::path path = mFolder / std::filesystem::u8path(name);
mPending.push_back([path, data, done]()
{
done(fsSavedFile::save(path, data) ? fsCloudSaveResult::eOK : fsCloudSaveResult::eERROR);
});
}
void fsCloudSaveServiceLocalFolder::remove(const std::string& name, DoneCallback done)
{
const std::filesystem::path path = mFolder / std::filesystem::u8path(name);
mPending.push_back([path, done]()
{
std::error_code error;
const bool removed = std::filesystem::remove(path, error);
done(error ? fsCloudSaveResult::eERROR : (removed ? fsCloudSaveResult::eOK : fsCloudSaveResult::eNOT_FOUND));
});
}
void fsCloudSaveServiceLocalFolder::update()
{
// Callbacks may queue more work; that runs on the next update.
std::vector<std::function<void()>> pending;
pending.swap(mPending);
for (auto& call : pending)<--- Variable 'call' can be declared as reference to const
{
call();
}
}
void fsCloudSaveServiceLocalFolder::shutdown()
{
update();
}