/* 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_NOTIFICATION_NOTIFICATIONPARENT_H_
#define DOM_NOTIFICATION_NOTIFICATIONPARENT_H_

#include "mozilla/dom/DOMTypes.h"
#include "mozilla/dom/notification/PNotificationParent.h"
#include "mozilla/ipc/PBackgroundParent.h"

namespace mozilla::dom::notification {

enum class CloseMode;

enum class AlertTopic : uint8_t {
  Disable,
  Settings,
  Click,
  Show,
  // Either closed or error.
  // See ToAlertTopic about why we have both Finished and Closed.
  Finished,
  Closed,
};

struct NotificationParentArgs {
  NotNull<nsCOMPtr<nsIPrincipal>> mPrincipal;
  NotNull<nsCOMPtr<nsIPrincipal>> mEffectiveStoragePrincipal;
  bool mIsSecureContext;
  nsString mScope;
  IPCNotification mNotification;
};

class NotificationParent final : public PNotificationParent,
                                 public nsISupports,
                                 public SupportsWeakPtr {
  using IPCResult = mozilla::ipc::IPCResult;

 public:
  NS_DECL_ISUPPORTS

  nsresult HandleAlertTopic(AlertTopic aTopic);
  IPCResult RecvShow(Maybe<IPCImage>&& aIcon, ShowResolver&& aResolver);
  IPCResult RecvClose();

  static nsresult CreateOnMainThread(
      NotificationParentArgs&& mArgs,
      Endpoint<PNotificationParent>&& aParentEndpoint,
      PBackgroundParent::CreateNotificationParentResolver&& aResolver);

 private:
  explicit NotificationParent(NotificationParentArgs&& aArgs)
      : mId(aArgs.mNotification.id()), mArgs(std::move(aArgs)) {};
  ~NotificationParent() = default;

  nsresult Show(Maybe<IPCImage>&& aIcon);
  nsresult FireClickEvent();

  void Unregister();

  Maybe<NotificationParent::ShowResolver> mResolver;

  // The ID generated by nsIAlertNotification during Show() function. It may
  // stay empty if the function fails.
  nsString mId;
  const NotificationParentArgs mArgs;

  // Whether it's now a dangling actor without corresponding OS notification,
  // either because it's closed or denied permission. We don't have to call
  // CloseAlert if this is the case.
  bool mDangling = false;

  // State tracking for async SafeBrowsing checks (bug 1986300).
  // When a SafeBrowsing classification is in progress, we track whether a
  // close was requested before the check completes.
  bool mShowPending = false;
  bool mClosePending = false;
};

}  // namespace mozilla::dom::notification

#endif  // DOM_NOTIFICATION_NOTIFICATIONPARENT_H_
