You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

120 lines
2.7 KiB

5 years ago
#include <fstream>
#include <iostream>
#include <orders.hpp>
5 years ago
void from_json(const json &j, order &order) {
j.at("name").get_to(order.name);
j.at("address").get_to(order.address);
j.at("phone").get_to(order.phone);
j.at("email").get_to(order.email);
j.at("id").get_to(order.id);
}
void to_json(nlohmann::json &j, const order &order) {
j = json{{"name", order.name},
{"address", order.address},
{"phone", order.phone},
{"email", order.email},
{"id", order.id}};
}
5 years ago
void orders::load() {
try {
5 years ago
json j;
5 years ago
std::fstream f(get_path());
5 years ago
f >> j;
j.get_to(data);
5 years ago
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
}
}
5 years ago
void orders::sort() {
// std::cout << "sorting..." << std::endl;
// std::vector<json> vec;
// vec.reserve(data.size());
// for (auto &el : *this) {
// vec.push_back(el);
// }
// std::stable_sort(vec.begin(), vec.end(), [](const auto &a, const auto &b) {
// int aid = a["id"];
// int bid = b["id"];
// if (aid > bid) {
// return 1;
// }
// if (aid < bid) {
// return -1;
// }
// return 0;
// });
// clear();
// for (const auto &json : vec) {
// push_back(json);
// }
}
5 years ago
const fs::path &orders::get_path() {
static fs::path orders_json;
if (orders_json.empty())
orders_json = data_directory.get_path() / "orders.json";
return orders_json;
}
5 years ago
orders::orders(const with_data_directory &dir) : data_directory(dir) {
if (fs::exists(get_path())) {
load();
} else {
write();
5 years ago
}
}
void orders::write() {
5 years ago
try {
std::ofstream of(get_path());
5 years ago
json j{data};
of << j;
5 years ago
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
}
5 years ago
}
orders::~orders() { write(); }
5 years ago
auto max_element(
json::iterator begin, json::iterator end,
std::function<bool(const json::iterator &, const json::iterator &)> cmp) {
auto largest = begin;
if (begin == end)
return end;
for (; begin != end; begin++)
if (cmp(largest, begin))
largest = begin;
return largest;
}
void orders::push(json data) {
5 years ago
// int id = 0;
// if (size() > 0) {
// const auto res =
// max_element(begin(), end(), [](const json &a, const json &b) {
// std::cout << "max_element " << a["id"] << b["id"] << std::endl;
// std::cout << a["id"] << std::endl;
// std::cout << b["id"] << std::endl;
// return a["id"] < b["id"];
// });
// id = (*res)["id"];
// }
// std::cout << "--\n" << id << std::endl;
// data["id"] = id + 1;
// std::cout << data["id"] << std::endl;
order o;
data["id"] = 0;
data.get_to(o);
std::cout << data << std::endl;
data.push_back(o);
}