#pragma once

#include <QObject>
#include <QString>
#include <QUrl>
#include <format>
#include <qcoreapplication.h>
#include <vector>
#include "logger.hpp"

class PlaylistController : public QObject {
  Q_OBJECT
  Q_PROPERTY(QUrl currentVideoSource READ currentVideoSource NOTIFY
                 currentVideoSourceChanged)

public:
  explicit PlaylistController(QObject *parent = nullptr) : QObject(parent) {}

  QUrl currentVideoSource() const { return m_currentVideoSource; }

  Q_INVOKABLE void loadNextVideo() {
    if (m_queue.size() == 0) {
      Logger::info("Nothing left to play");
      m_playing = false;
      return;
    }

    QString video = m_queue.front();
    Logger::info(std::format("Playing: {} in video {}", video.toStdString(), 1));
    m_queue.erase(m_queue.begin());

    QUrl newUrl = QUrl::fromLocalFile(video);
    if (m_currentVideoSource != newUrl) {
      m_currentVideoSource = newUrl;
      emit currentVideoSourceChanged();
    }
  }
  
  // Tengo que rehacer esto en algun momento para que tome la url y la procese en otro thread
  // Y ya que me pongo con ello usar el doble buffer y permitir cargar listas enteras
  Q_INVOKABLE void addToQueue(const QString path) {
    int n_elements = m_queue.size();

    m_queue.push_back(path);
    Logger::info(std::format("Adding: {}", path.toStdString()));

    if (n_elements == 0 && !m_playing) {
      m_playing = true;
      loadNextVideo();
    }
  }

signals:
  void currentVideoSourceChanged();

private:
  bool m_playing = false;
  std::vector<QString> m_queue = std::vector<QString>();
  QUrl m_currentVideoSource = QString("");
};
