#include "sqlite_repository.hpp"
#include "test_support.hpp"
#include "window.hpp"
#include <QApplication>
#include <QCommandLineParser>
#include <QDir>
#include <QStandardPaths>
#include <iostream>
int main(int argc, char **argv) {
  QApplication app(argc, argv);
  app.setApplicationName("AppFabrikOrderLab");
  app.setStyle("Fusion");
  app.setStyleSheet(
      "QWidget { font-size: 14px; } QPushButton { padding: 7px 12px; } "
      "QLineEdit, QSpinBox { min-height: 28px; } QTableView { gridline-color: "
      "#d8e2ec; alternate-background-color: #f2f6fb; } QHeaderView::section { "
      "padding: 8px; font-weight: bold; }");
  QCommandLineParser parser;
  parser.addHelpOption();
  parser.addOption({"database", "Use this SQLite database", "path"});
  parser.addOption(
      {"screenshot",
       "Render a screenshot and exit. Requires a new explicit database path",
       "path"});
  parser.process(app);
  auto path = parser.value("database");
  if (parser.isSet("screenshot") && (path.isEmpty() || QFile::exists(path))) {
    std::cerr << "Screenshot mode requires a new --database path\n";
    return 1;
  }
  if (path.isEmpty()) {
    const auto directory =
        QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    if (!QDir().mkpath(directory))
      return 1;
    path = directory + "/orders.sqlite";
  }
  orders::SqliteRepository repository(path);
  orders::OrderService service(repository);
  auto loaded = service.list();
  if (!orders::succeeded(loaded)) {
    std::cerr << std::get<orders::Error>(loaded).message << '\n';
    return 1;
  }
  if (parser.isSet("screenshot") &&
      !orders::succeeded(service.replace(samples())))
    return 1;
  orders::OrderWindow window(service);
  window.show();
  if (parser.isSet("screenshot")) {
    const auto image = parser.value("screenshot");
    QTimer::singleShot(250, &window,
                       [&] { app.exit(window.grab().save(image) ? 0 : 1); });
  }
  return app.exec();
}
