// SPDX-FileCopyrightText: 2021 Johannes Loher
//
// SPDX-License-Identifier: MIT

import { logger } from "../utils/logger";
import { getNotificationsSafe } from "../utils/utils";

/**
 * @typedef {Object} NotificationOptions
 * @property {boolean} [permanent=false]
 * @property {boolean} [log=false]
 */

/**
 * @typedef {(message: string, options?: NotificationOptions) => void} NotificationFunction
 */

/**
 * @typedef {"info" | "warn" | "error"} NotificationType
 */

/**
 * @param {NotificationType} type The type of the notification
 * @returns {NotificationFunction}
 */
function getNotificationFunction(type) {
  return (message, { permanent = false, log = false } = {}) => {
    if (ui.notifications) {
      ui.notifications[type](message, { permanent });
      if (log) {
        logger[type](message);
      }
    } else {
      logger[type](message);
    }
  };
}

/**
 * @param {string} message
 * @param {NotificationType} type
 * @param {NotificationOptions} [options={}]
 */
function notify(message, type, { permanent = false, log = false } = {}) {
  const notifications = getNotificationsSafe();
  if (notifications) {
    notifications.notify(message, type, { permanent });
    if (log) {
      logger.getLoggingFunction(type)(message);
    }
  } else {
    logger.getLoggingFunction(type)(message);
  }
}

export const notifications = Object.freeze({
  info: getNotificationFunction("info"),
  warn: getNotificationFunction("warn"),
  error: getNotificationFunction("error"),
  notify,
});
