import { coalesce } from "./arrays.mjs";
import { isString } from "./types.mjs";
import { localize } from "../../nls.mjs";
function exceptionToErrorMessage(exception, verbose) {
  if (verbose && (exception.stack || exception.stacktrace)) {
    return localize("stackTrace.format", "{0}: {1}", detectSystemErrorMessage(exception), stackToString(exception.stack) || stackToString(exception.stacktrace));
  }
  return detectSystemErrorMessage(exception);
}
function stackToString(stack) {
  if (Array.isArray(stack)) {
    return stack.join("\n");
  }
  return stack;
}
function detectSystemErrorMessage(exception) {
  if (typeof exception.code === "string" && typeof exception.errno === "number" && typeof exception.syscall === "string") {
    return localize("nodeExceptionMessage", "A system error occurred ({0})", exception.message);
  }
  return exception.message || localize("error.defaultMessage", "An unknown error occurred. Please consult the log for more details.");
}
function toErrorMessage(error = null, verbose = false) {
  if (!error) {
    return localize("error.defaultMessage", "An unknown error occurred. Please consult the log for more details.");
  }
  if (Array.isArray(error)) {
    const errors = coalesce(error);
    const msg = toErrorMessage(errors[0], verbose);
    if (errors.length > 1) {
      return localize("error.moreErrors", "{0} ({1} errors in total)", msg, errors.length);
    }
    return msg;
  }
  if (isString(error)) {
    return error;
  }
  if (error.detail) {
    const detail = error.detail;
    if (detail.error) {
      return exceptionToErrorMessage(detail.error, verbose);
    }
    if (detail.exception) {
      return exceptionToErrorMessage(detail.exception, verbose);
    }
  }
  if (error.stack) {
    return exceptionToErrorMessage(error, verbose);
  }
  if (error.message) {
    return error.message;
  }
  return localize("error.defaultMessage", "An unknown error occurred. Please consult the log for more details.");
}
export {
  toErrorMessage
};
