/*
 * Strawberry Music Player
 * Copyright 2018-2023, Jonas Kvinge <jonas@jkvinge.net>
 *
 * Strawberry is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Strawberry is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Strawberry.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#ifndef LISTENBRAINZSCROBBLER_H
#define LISTENBRAINZSCROBBLER_H

#include "config.h"

#include <QtGlobal>
#include <QObject>
#include <QList>
#include <QVariant>
#include <QByteArray>
#include <QString>
#include <QUrl>
#include <QJsonDocument>
#include <QTimer>

#include "core/shared_ptr.h"
#include "core/song.h"
#include "scrobblerservice.h"
#include "scrobblercache.h"
#include "scrobblemetadata.h"

class QNetworkReply;

class ScrobblerSettings;
class NetworkAccessManager;
class LocalRedirectServer;

class ListenBrainzScrobbler : public ScrobblerService {
  Q_OBJECT

 public:
  explicit ListenBrainzScrobbler(SharedPtr<ScrobblerSettings> settings, SharedPtr<NetworkAccessManager> network, QObject *parent = nullptr);
  ~ListenBrainzScrobbler() override;

  static const char *kName;
  static const char *kSettingsGroup;

  void ReloadSettings() override;
  void LoadSession();

  bool enabled() const override { return enabled_; }
  bool authenticated() const override { return !access_token_.isEmpty() && !user_token_.isEmpty(); }
  bool submitted() const override { return submitted_; }
  QString user_token() const { return user_token_; }

  void Authenticate();
  void Logout();
  void ShowConfig();
  void Submit() override;
  void UpdateNowPlaying(const Song &song) override;
  void ClearPlaying() override;
  void Scrobble(const Song &song) override;
  void Love() override;

  enum class ReplyResult {
    Success,
    ServerError,
    APIError
  };

 signals:
  void AuthenticationComplete(const bool success, const QString &error = QString());

 public slots:
  void WriteCache() override { cache_->WriteCache(); }

 private slots:
  void RedirectArrived();
  void AuthenticateReplyFinished(QNetworkReply *reply);
  void RequestNewAccessToken() { RequestAccessToken(); }
  void UpdateNowPlayingRequestFinished(QNetworkReply *reply);
  void ScrobbleRequestFinished(QNetworkReply *reply, ScrobblerCacheItemPtrList cache_items);
  void LoveRequestFinished(QNetworkReply *reply);

 private:
  QNetworkReply *CreateRequest(const QUrl &url, const QJsonDocument &json_doc);
  ReplyResult GetJsonObject(QNetworkReply *reply, QJsonObject &json_obj, QString &error_description);
  QJsonObject JsonTrackMetadata(const ScrobbleMetadata &metadata) const;
  void AuthError(const QString &error);
  void Error(const QString &error, const QVariant &debug = QVariant());
  void RequestAccessToken(const QUrl &redirect_url = QUrl(), const QString &code = QString());
  void StartSubmit(const bool initial = false) override;
  void CheckScrobblePrevSong();

  SharedPtr<NetworkAccessManager> network_;
  ScrobblerCache *cache_;
  LocalRedirectServer *server_;
  bool enabled_;
  QString user_token_;
  QString access_token_;
  qint64 expires_in_;
  QString token_type_;
  QString refresh_token_;
  quint64 login_time_;
  bool submitted_;
  Song song_playing_;
  bool scrobbled_;
  quint64 timestamp_;
  QTimer refresh_login_timer_;
  QTimer timer_submit_;
  bool submit_error_;

  bool prefer_albumartist_;

  QList<QNetworkReply*> replies_;
};

#endif  // LISTENBRAINZSCROBBLER_H
