#ifndef MEDIAHANDLER_H
#define MEDIAHANDLER_H

#include <QObject>
#include <QMediaDevices>

QT_BEGIN_NAMESPACE
class QMediaCaptureSession;
class QVideoSink;
class QAudioInput;
class QCamera;
class QMediaRecorder;
QT_END_NAMESPACE

// TODO: create simple structs to represent camera and audio input devices

/// MediaHandler allows you to preview and capture video, audio, and screen
class MediaHandler : public QObject
{
  Q_OBJECT

public:
  explicit MediaHandler(QObject *parent = nullptr);
  ~MediaHandler();

  enum State
  {
    OFF = 0,
    PREPARING,
    ON,
    RECORDING
  };
  State state() const;

  enum CaptureMode
  {
    AUDIO_ONLY = 0,
    CAMERA,
    SCREEN
  };
  CaptureMode captureMode() const;

  QVideoSink *videoSink() const;

  // QList<CameraDevices>
  // QList<AudioDevices>

public slots:
  /// Only impacts the next time start is called
  void setCaptureMode(CaptureMode);

  /// Start preview: OFF → ON
  void startPreview(QVideoSink *sink = nullptr);

  /// Start recording: OFF → ON → RECORDING (auto-records when ready)
  ///                  or ON → RECORDING (immediate)
  void startRecording(QVideoSink *sink = nullptr);

  /// Clean up resources, will stop all capture, recording, preview
  void stop();

  void recordCancel();
  void recordStop();

  // void setCameraDevice();
  // void setAudioInputDevice();

signals:
  /// User has denied mic permission, and must go to settings to enable
  void micPermissionDenied();
  /// User has denied camera permission, and must go to settings to enable
  void cameraPermissionDenied();

  void captureModeChanged();
  void stateChanged();

  void recordingComplete(const QUrl &absoluteFilePath, qint64 durationMs, const QString &mimeType);

  void errorOccurred(const QString &);

private:
  QMediaCaptureSession *m_captureSession;
  QAudioInput *m_audioInput;
  QCamera *m_camera;
  QVideoSink *m_videoSink;
  QMediaRecorder *m_recorder;
  QMediaDevices m_devices;

  CaptureMode m_captureMode = CAMERA;
  State m_state = OFF;
  void setState(State);

  void startCapture(QVideoSink *sink);

  bool m_pendingRecord = false;
  bool m_cancelledRecording = false;
};

#endif //MEDIAHANDLER_H
