/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef DOM_MEDIA_MEDIACONTROL_CONTENTMEDIACONTROLLER_H_
#define DOM_MEDIA_MEDIACONTROL_CONTENTMEDIACONTROLLER_H_

#include "MediaControlKeySource.h"
#include "MediaStatusManager.h"
#include "mozilla/DefineEnum.h"
#include "mozilla/dom/AudioSessionBinding.h"

namespace mozilla::dom {

class BrowsingContext;

// Direction of an audio-focus interrupt dispatched to content media receivers.
// Suspend silences the tab's potentially audible sources on a focus loss;
// Resume resumes the ones the interrupt suspended on a focus gain.
MOZ_DEFINE_ENUM_CLASS_WITH_BASE_AND_TOSTRING(AudioFocusInterruptAction, uint8_t,
                                             (Suspend, Resume));

/**
 * ContentMediaControlKeyReceiver is an interface which is used to receive media
 * control key sent from the chrome process.
 */
class ContentMediaControlKeyReceiver {
 public:
  NS_INLINE_DECL_PURE_VIRTUAL_REFCOUNTING

  // Return nullptr if the top level browsing context is no longer alive.
  static ContentMediaControlKeyReceiver* Get(BrowsingContext* aBC);

  // Use this method to handle the event from `ContentMediaAgent`.
  virtual void HandleMediaKey(MediaControlKey aKey,
                              const MediaControlActionParams& aParams = {}) = 0;

  virtual bool IsPlaying() const = 0;

  // Audio-focus interrupt verbs. These are distinct from the user Pause/Play
  // media-key path: an interrupt suspends every potentially audible receiver
  // and a later resume resumes only what the interrupt suspended. Default no-op
  // so that receivers which do not participate in interrupt handling need no
  // change.
  virtual void SuspendForInterrupt() {}
  virtual void ResumeFromInterrupt() {}

  // Dispatch an audio-focus interrupt. ContentMediaController overrides this to
  // fan the interrupt out to its potentially audible receivers; leaf receivers
  // rely on the suspend/resume verbs above and leave this as a no-op.
  virtual void HandleAudioFocusInterrupt(AudioFocusInterruptAction aAction) {}
};

/**
 * ContentMediaAgent is an interface which we use to (1) propoagate media
 * related information from the content process to the chrome process (2) act an
 * event source to dispatch media control key to its listeners.
 *
 * If the media would like to know the media control key, then media MUST
 * inherit from ContentMediaControlKeyReceiver, and register themselves to
 * ContentMediaAgent. Whenever media control key delivers, ContentMediaAgent
 * would notify all its receivers. In addition, whenever controlled media
 * changes its playback status or audible state, they should update their status
 * update via ContentMediaAgent.
 */
class ContentMediaAgent : public IMediaInfoUpdater {
 public:
  // Return nullptr if the top level browsing context is no longer alive.
  static ContentMediaAgent* Get(BrowsingContext* aBC);

  // IMediaInfoUpdater Methods
  void NotifyMediaPlaybackChanged(uint64_t aBrowsingContextId,
                                  MediaPlaybackState aState) override;
  void NotifyMediaAudibleChanged(
      uint64_t aBrowsingContextId, MediaAudibleState aState,
      ControlType aType = ControlType::eControllable,
      AudioSessionType aSessionType = AudioSessionType::Playback) override;
  void SetIsInPictureInPictureMode(uint64_t aBrowsingContextId,
                                   bool aIsInPictureInPictureMode) override;
  void SetDeclaredPlaybackState(uint64_t aBrowsingContextId,
                                MediaSessionPlaybackState aState) override;
  void NotifySessionCreated(uint64_t aBrowsingContextId) override;
  void NotifySessionDestroyed(uint64_t aBrowsingContextId) override;
  void UpdateMetadata(uint64_t aBrowsingContextId,
                      const Maybe<MediaMetadataBase>& aMetadata) override;
  void EnableAction(uint64_t aBrowsingContextId,
                    MediaSessionAction aAction) override;
  void DisableAction(uint64_t aBrowsingContextId,
                     MediaSessionAction aAction) override;
  void NotifyMediaFullScreenState(uint64_t aBrowsingContextId,
                                  bool aIsInFullScreen) override;
  void UpdatePositionState(uint64_t aBrowsingContextId,
                           const Maybe<PositionState>& aState) override;
  void UpdateGuessedPositionState(uint64_t aBrowsingContextId,
                                  const nsID& aMediaId,
                                  const Maybe<PositionState>& aState) override;

  // Use these methods to register/unregister `ContentMediaControlKeyReceiver`
  // in order to listen to media control key events. The aType parameter
  // indicates whether the receiver participates in the full media-control
  // lifecycle (eControllable, the default) or only accepts volume/mute keys
  // (eUncontrollable).
  virtual void AddReceiver(ContentMediaControlKeyReceiver* aReceiver,
                           ControlType aType = ControlType::eControllable) = 0;
  virtual void RemoveReceiver(
      ContentMediaControlKeyReceiver* aReceiver,
      ControlType aType = ControlType::eControllable) = 0;
};

/**
 * ContentMediaController exists in per inner window, which has a responsibility
 * to update the content media state to MediaController (ContentMediaAgent) and
 * delivers MediaControlKey to its receiver in order to control media in the
 * content page (ContentMediaControlKeyReceiver).
 */
class ContentMediaController final : public ContentMediaAgent,
                                     public ContentMediaControlKeyReceiver {
 public:
  NS_INLINE_DECL_REFCOUNTING(ContentMediaController, override)

  explicit ContentMediaController(uint64_t aId);
  // ContentMediaAgent methods
  void AddReceiver(ContentMediaControlKeyReceiver* aListener,
                   ControlType aType = ControlType::eControllable) override;
  void RemoveReceiver(ContentMediaControlKeyReceiver* aListener,
                      ControlType aType = ControlType::eControllable) override;

  // ContentMediaControlKeyReceiver method
  void HandleMediaKey(MediaControlKey aKey,
                      const MediaControlActionParams& aParams = {}) override;

  // Dispatch an audio-focus interrupt to every potentially audible receiver in
  // both the controllable and uncontrollable buckets.
  void HandleAudioFocusInterrupt(AudioFocusInterruptAction aAction) override;

  bool IsAudioInterruptedByPlatform() const {
    return mAudioInterruptedByPlatform;
  }

 private:
  ~ContentMediaController() = default;

  // We don't need this method, so make it as private and simply return false.
  virtual bool IsPlaying() const override { return false; }

  void PauseOrStopMedia();

  nsTArray<RefPtr<ContentMediaControlKeyReceiver>> mControllableReceivers;
  nsTArray<RefPtr<ContentMediaControlKeyReceiver>> mUncontrollableReceivers;

  // True while the platform has interrupted the tab's audio (an audio-focus
  // loss): no audible sound may start while set, so page-initiated start and
  // resume are gated; cleared when the platform ends the interrupt.
  bool mAudioInterruptedByPlatform = false;
};

}  // namespace mozilla::dom

#endif  // DOM_MEDIA_MEDIACONTROL_CONTENTMEDIACONTROLLER_H_
