#include "mediapreviewdialog.h"
#include <QAudioOutput>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QMediaPlayer>
#include <QPushButton>
#include <QVBoxLayout>
#include <QVideoWidget>

MediaPreviewDialog::MediaPreviewDialog(QWidget *parent)
    : QDialog(parent)
{
  setWindowTitle("Media Preview");
  resize(480, 360);
  setModal(true);

  m_videoWidget = new QVideoWidget(this);
  m_player = new QMediaPlayer(this);
  m_audioOutput = new QAudioOutput(this);
  m_player->setAudioOutput(m_audioOutput);

  m_cancelButton = new QPushButton("Cancel", this);
  m_sendButton = new QPushButton("Send", this);
  m_sendButton->setDefault(true);

  auto *buttonLayout = new QHBoxLayout();
  buttonLayout->addWidget(m_cancelButton);
  buttonLayout->addStretch();
  buttonLayout->addWidget(m_sendButton);

  auto *layout = new QVBoxLayout(this);
  layout->addWidget(m_videoWidget, 1);
  layout->addLayout(buttonLayout);

  m_cancelButton->hide();
  m_sendButton->hide();

  connect(m_sendButton, &QPushButton::clicked, this, &QDialog::accept);
  connect(m_cancelButton, &QPushButton::clicked, this, &QDialog::reject);
}

QVideoSink *MediaPreviewDialog::videoSink() const
{
  return m_videoWidget->videoSink();
}

void MediaPreviewDialog::showRecording()
{
  m_player->stop();
  m_player->setVideoOutput(nullptr);
  m_player->setSource(QUrl());
  m_cancelButton->hide();
  m_sendButton->hide();
  show();
}

void MediaPreviewDialog::showPreview(const QUrl &mediaUrl)
{
  m_cancelButton->show();
  m_sendButton->show();
  m_player->setVideoOutput(m_videoWidget);
  m_player->setSource(mediaUrl);
  m_player->setLoops(QMediaPlayer::Infinite);
  m_player->play();
}

void MediaPreviewDialog::reset()
{
  m_player->stop();
  m_player->setVideoOutput(nullptr);
  m_player->setSource(QUrl());
  m_cancelButton->hide();
  m_sendButton->hide();
  hide();
}

void MediaPreviewDialog::keyReleaseEvent(QKeyEvent *event)
{
  if (event->key() == Qt::Key_Space && !event->isAutoRepeat())
  {
    emit spaceReleased();
    return;
  }
  QDialog::keyReleaseEvent(event);
}
