#include "bridge.h"

#include <QApplication>
#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QIcon>
#include <QMainWindow>
#include <QUrl>
#include <QWebChannel>
#include <QWebEnginePage>
#include <QWebEngineProfile>
#include <QWebEngineSettings>
#include <QWebEngineView>

namespace {

QString findFrontendRoot() {
  const QStringList candidates = {
      QDir(QCoreApplication::applicationDirPath()).absoluteFilePath("../share/labelnova/frontend"),
      QDir(QCoreApplication::applicationDirPath()).absoluteFilePath("../frontend"),
      QDir(QCoreApplication::applicationDirPath()).absoluteFilePath("../../frontend"),
      QDir(QCoreApplication::applicationDirPath()).absoluteFilePath("../../../"),
      QDir(QCoreApplication::applicationDirPath()).absoluteFilePath("../../.."),
  };

  for (const auto &candidate : candidates) {
    if (QFileInfo::exists(QDir(candidate).absoluteFilePath("index.html"))) {
      return QDir(candidate).absolutePath();
    }
  }
  return {};
}

}  // namespace

int main(int argc, char *argv[]) {
  QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
  QApplication app(argc, argv);
  QCoreApplication::setOrganizationName("LabelNova");
  QCoreApplication::setApplicationName("LabelNova");
  QCoreApplication::setApplicationVersion(QStringLiteral(LABELNOVA_APP_VERSION));

  QMainWindow window;
  window.resize(1440, 920);
  window.setWindowTitle(QStringLiteral("LabelNova"));
  window.setWindowIcon(QIcon(QStringLiteral(":/icons/labelnova.svg")));

  auto *view = new QWebEngineView(&window);
  auto *channel = new QWebChannel(view->page());
  auto *bridge = new DesktopBridge(&window, &window);
  channel->registerObject(QStringLiteral("desktopBridge"), bridge);
  view->page()->setWebChannel(channel);
  view->settings()->setAttribute(QWebEngineSettings::LocalStorageEnabled, true);
  view->settings()->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls, true);
  view->settings()->setAttribute(QWebEngineSettings::JavascriptCanAccessClipboard, true);

  const auto frontendRoot = findFrontendRoot();
  bridge->setFrontendRoot(frontendRoot);

  if (!frontendRoot.isEmpty()) {
    const auto indexPath = QDir(frontendRoot).absoluteFilePath("index.html");
    view->load(QUrl::fromLocalFile(indexPath));
  }

  window.setCentralWidget(view);
  window.show();
  return app.exec();
}
