/* 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/. */

#include "MediaControlKeySource.h"

#include "MediaControlService.h"
#include "MediaControlUtils.h"
#include "MediaController.h"
#include "mozilla/Logging.h"

namespace mozilla::dom {

// avoid redefined macro in unified build
#undef LOG_SOURCE
#define LOG_SOURCE(msg, ...)                     \
  MOZ_LOG_FMT(gMediaControlLog, LogLevel::Debug, \
              "MediaControlKeySource={}, " msg, fmt::ptr(this), ##__VA_ARGS__)

#undef LOG_KEY
#define LOG_KEY(msg, key, ...)                                   \
  MOZ_LOG_FMT(gMediaControlLog, LogLevel::Debug,                 \
              "MediaControlKeyHandler={}, " msg, fmt::ptr(this), \
              ToMediaControlKeyStr(key), ##__VA_ARGS__);

void MediaControlKeyHandler::OnActionPerformed(
    const MediaControlAction& aAction) {
  LOG_KEY("OnActionPerformed '{}'", aAction.mKey);

  RefPtr<MediaControlService> service = MediaControlService::GetService();
  MOZ_ASSERT(service);
  RefPtr<IMediaController> controller = service->GetMainController();
  if (!controller) {
    return;
  }

  if (aAction.mKey.isNothing()) {
    MOZ_ASSERT_UNREACHABLE("Error : undefined media key!");
    return;
  }
  switch (aAction.mKey.value()) {
    case MediaControlKey::Focus:
      controller->Focus();
      return;
    case MediaControlKey::Play:
      controller->Play();
      return;
    case MediaControlKey::Pause:
      controller->Pause();
      return;
    case MediaControlKey::Playpause: {
      if (controller->IsPlaying()) {
        controller->Pause();
      } else {
        controller->Play();
      }
      return;
    }
    case MediaControlKey::Previoustrack:
      controller->PrevTrack();
      return;
    case MediaControlKey::Nexttrack:
      controller->NextTrack();
      return;
    case MediaControlKey::Seekbackward: {
      const MediaControlActionParams& params = aAction.mParams;
      MOZ_ASSERT(params.mRelativeSeekOffset);
      controller->SeekBackward(fmin(params.mRelativeSeekOffset.value(), 10.0));
      return;
    }
    case MediaControlKey::Seekforward: {
      const MediaControlActionParams& params = aAction.mParams;
      MOZ_ASSERT(params.mRelativeSeekOffset);
      controller->SeekForward(fmin(params.mRelativeSeekOffset.value(), 10.0));
      return;
    }
    case MediaControlKey::Skipad:
      controller->SkipAd();
      return;
    case MediaControlKey::Seekto: {
      const MediaControlActionParams& params = aAction.mParams;
      MOZ_ASSERT(params.mAbsolute);
      controller->SeekTo(params.mAbsolute->mSeekTime,
                         params.mAbsolute->mFastSeek);
      return;
    }
    case MediaControlKey::Setvolume: {
      const MediaControlActionParams& params = aAction.mParams;
      MOZ_ASSERT(params.mVolume);
      controller->SetVolume(params.mVolume.value());
      return;
    }
    case MediaControlKey::Mute:
      controller->Mute();
      return;
    case MediaControlKey::Unmute:
      controller->Unmute();
      return;
    case MediaControlKey::Stop:
      controller->Stop();
      return;
    default:
      MOZ_ASSERT_UNREACHABLE("Error : undefined media key!");
      return;
  }
}

MediaControlKeySource::MediaControlKeySource()
    : mPlaybackState(MediaSessionPlaybackState::None) {}

void MediaControlKeySource::AddListener(MediaControlKeyListener* aListener) {
  MOZ_ASSERT(aListener);
  LOG_SOURCE("Add listener {}", fmt::ptr(aListener));
  mListeners.AppendElement(aListener);
}

void MediaControlKeySource::RemoveListener(MediaControlKeyListener* aListener) {
  MOZ_ASSERT(aListener);
  LOG_SOURCE("Remove listener {}", fmt::ptr(aListener));
  mListeners.RemoveElement(aListener);
}

size_t MediaControlKeySource::GetListenersNum() const {
  return mListeners.Length();
}

void MediaControlKeySource::Close() {
  LOG_SOURCE("Close source");
  mListeners.Clear();
}

void MediaControlKeySource::SetPlaybackState(MediaSessionPlaybackState aState) {
  if (mPlaybackState == aState) {
    return;
  }
  LOG_SOURCE("SetPlaybackState '{}'", ToMediaSessionPlaybackStateStr(aState));
  mPlaybackState = aState;
}

MediaSessionPlaybackState MediaControlKeySource::GetPlaybackState() const {
  return mPlaybackState;
}

}  // namespace mozilla::dom
