#include <QDebug>
#include <QGuiApplication>
#include <QQmlContext>
#include <QQuickView>
#include <QStandardPaths>
#include <QTimer>

#include <gst/gst.h>

#include "RtspPlayer.h"
#include "VideoItem.h"

int main(int argc, char *argv[])
{
   gst_init(&argc, &argv);

   QGuiApplication app(argc, argv);
   app.setApplicationName(QStringLiteral("rtspviewer.barrydegraaff"));

   qInfo() << "Application data path:"
           << QStandardPaths::writableLocation(
                 QStandardPaths::AppDataLocation
              );

   qmlRegisterType<VideoItem>(
      "Barry.RtspViewer",
      1,
      0,
      "VideoItem"
   );

   RtspPlayer player;

   QQuickView view;
   view.setResizeMode(QQuickView::SizeRootObjectToView);

   view.rootContext()->setContextProperty(
      QStringLiteral("rtspPlayer"),
      &player
   );

   qInfo() << "Loading QML";

   view.setSource(
      QUrl(QStringLiteral("qrc:/qml/Main.qml"))
   );

   if (view.status() == QQuickView::Error) {
      qCritical() << "QML failed to load.";
      gst_deinit();
      return 1;
   }

   qInfo() << "QML load completed";

   QObject::connect(
      &view,
      &QWindow::visibleChanged,
      [](bool visible) {
         qInfo() << "Window visible:" << visible;
      }
   );

   QObject::connect(
      &view,
      &QWindow::activeChanged,
      [&view]() {
         qInfo() << "Window active:" << view.isActive();
      }
   );

   QObject::connect(
      &app,
      &QGuiApplication::applicationStateChanged,
      [](Qt::ApplicationState state) {
         qInfo() << "Application state:" << state;
      }
   );

   qInfo() << "Showing application window";
   view.show();

   QTimer::singleShot(
      0,
      &view,
      [&view]() {
         qInfo() << "Window exposed:" << view.isExposed();
         view.raise();
         view.requestActivate();
      }
   );

   const int result = app.exec();

   gst_deinit();
   return result;
}
