import { WarningException, WaitingChangeException, ErrorException, ObjectUtils, SilentException } from "@sankhyalabs/core";
export class SnkErrorHandler {
  constructor(app) {
    this._app = app;
    window.addEventListener("error", evt => this.errorHandler(evt));
    window.addEventListener("unhandledrejection", evt => this.rejectionHandler(evt));
  }
  getMessage(key, params) {
    return this._app.messagesBuilder.getMessage(key, params);
  }
  rejectionHandler(evt) {
    const reason = evt.reason;
    //Promisse rejeitada com WaitingChangeException, não precisam
    //ser notificadas pelo usuário.
    if (!(reason instanceof WaitingChangeException)) {
      if (reason) {
        this.processException(reason);
      }
      else {
        this._app.isDebugMode().then((isDebug) => {
          if (isDebug) {
            this._app.error(this.getMessage("snkErrorHandler.title.promiseRejected"), this.getMessage("snkErrorHandler.message.undeterminedPromiseRejection"));
          }
        });
      }
    }
  }
  errorHandler(evt) {
    this.processException(evt.error);
  }
  buildErrorCodeHTML(errorCode) {
    const cannotOpenHelpMessage = this.getMessage("snkErrorHandler.message.cannotOpenHelp");
    const errorCodeLabel = this.getMessage("snkErrorHandler.errorCode.label");
    const onclick = `try{window.workspace.openHelp('_tbcode:${errorCode}')} catch(e){alert('${cannotOpenHelpMessage}');}`;
    return `<br><a href="#" onclick="${onclick}">${errorCodeLabel}${errorCode}</a>`;
  }
  processException(exception) {
    if (exception.errorCode) {
      exception.message += this.buildErrorCodeHTML(exception.errorCode);
    }
    if (exception instanceof SilentException) {
      console.warn(this.getMessage("snkErrorHandler.message.silentExceptionIgnored"), exception);
    }
    else if (exception instanceof WaitingChangeException) {
      this._app.alert(exception.title, exception.message);
    }
    else if (exception instanceof WarningException) {
      this._app.alert(exception.title, exception.message);
    }
    else if (exception instanceof ErrorException) {
      this._app.error(exception.title, exception.message);
    }
    else {
      console.warn("Erro não tratado", exception);
      this._app.isDebugMode().then(isDebug => {
        if (isDebug) {
          if (exception instanceof Error) {
            this._app.error(exception.name, exception.message);
          }
          else {
            const title = (exception === null || exception === void 0 ? void 0 : exception.title) || this.getMessage("snkErrorHandler.title.errorDetected", undefined);
            const message = (typeof exception === "string") ? exception :
              exception.message || `${this.getMessage("snkErrorHandler.error.internal")} "${ObjectUtils.objectToString(exception)}"`;
            this._app.error(title, message);
          }
        }
      });
    }
  }
}
