#include "Project.hpp" #include #include #include #include #include #include #include namespace fs = std::filesystem; template void ReadItemList(ItemList& list, const fs::path& filePath) { std::ifstream ifs(filePath); if (ifs) { Json::Value root; ifs >> root; list = ItemList(root); } } Project::Project(const fs::path& rootPath) : mRootPath{ rootPath } , mRootPathString{ mRootPath.string() } , mDb(*this) { // TODO better diagnostic const char* kInvalidFormatErr = "Failed to load project: invalid format."; std::ifstream ifs(rootPath / "cplt_project.json"); if (!ifs) { std::string message; message += "Failed to load project file at '"; message += rootPath.string(); message += "'."; throw std::runtime_error(message); } { Json::Value root; ifs >> root; const auto& croot = root; // Use const reference so that accessors default to returning a null if not found, instead of silently creating new elements if (!croot.isObject()) { throw std::runtime_error(kInvalidFormatErr); } if (auto& name = croot["Name"]; name.isString()) { mName = name.asString(); } else { throw std::runtime_error(kInvalidFormatErr); } } auto itemsDir = mRootPath / "items"; ReadItemList(Products, itemsDir / "products.json"); ReadItemList(Factories, itemsDir / "factories.json"); ReadItemList(Customers, itemsDir / "customers.json"); } Project::Project(std::filesystem::path rootPath, std::string name) : mRootPath{ std::move(rootPath) } , mRootPathString{ mRootPath.string() } , mName{ std::move(name) } , mDb(*this) { } const fs::path& Project::GetPath() const { return mRootPath; } const std::string& Project::GetPathString() const { return mRootPathString; } const std::string& Project::GetName() const { return mName; } void Project::SetName(std::string name) { mName = std::move(name); } const TransactionModel& Project::GetTransactionsModel() const { return mDb; } TransactionModel& Project::GetTransactionsModel() { return mDb; } Json::Value Project::Serialize() { Json::Value root(Json::objectValue); root["Name"] = mName; return root; } template static void WriteItemList(ItemList& list, const fs::path& filePath) { std::ofstream ofs(filePath); ofs << list.Serialize(); } void Project::WriteToDisk() { std::ofstream ofs(mRootPath / "cplt_project.json"); ofs << this->Serialize(); auto itemsDir = mRootPath / "items"; fs::create_directories(itemsDir); WriteItemList(Products, itemsDir / "products.json"); WriteItemList(Factories, itemsDir / "factories.json"); WriteItemList(Customers, itemsDir / "customers.json"); }