export class LoadStateManager {
  constructor(appName = 'snk-application') {
    this._state = LoadStatus.DOM_LOADED;
    this._application = document.querySelector(appName);
    if (this._application === null) {
      console.warn(`application ${appName} not found, then state is loadded`);
      this.onStatusChange(LoadStatus.LOADED);
    }
    else {
      this._application.addEventListener('applicationLoaded', () => this.onStatusChange(LoadStatus.LOADED));
      this._application.addEventListener('applicationLoading', () => this.onStatusChange(LoadStatus.PRE_INITIALIZE));
      this.onStatusChange(LoadStatus.PRE_INITIALIZE);
    }
  }
  async onStatusChange(newStatus) {
    this._state = newStatus;
    (LoadStateManager.listenersByType.get(newStatus) || []).forEach((listener) => {
      listener();
    });
  }
  addListener(status, listener) {
    var _a;
    if (!LoadStateManager.listenersByType.has(status)) {
      LoadStateManager.listenersByType.set(status, []);
    }
    (_a = LoadStateManager.listenersByType.get(status)) === null || _a === void 0 ? void 0 : _a.push(listener);
    if (status === this._state) {
      listener();
    }
  }
  onPreInitialize(listener) {
    this.addListener(LoadStatus.PRE_INITIALIZE, listener);
    return this;
  }
  onLoaded(listener) {
    this.addListener(LoadStatus.LOADED, listener);
    return this;
  }
  getStatus() {
    return this._state;
  }
  isPreInitialize() {
    return this._state === LoadStatus.PRE_INITIALIZE;
  }
  isLoaded() {
    return this._state === LoadStatus.LOADED;
  }
  static get(type = LoadType.APP_LOAD) {
    if (!LoadStateManager.instanceByStatus.has(type)) {
      LoadStateManager.instanceByStatus.set(type, new LoadStateManager());
    }
    return LoadStateManager.instanceByStatus.get(type) || new LoadStateManager();
  }
}
LoadStateManager.instanceByStatus = new Map();
LoadStateManager.listenersByType = new Map();
export var LoadStatus;
(function (LoadStatus) {
  LoadStatus["DOM_LOADED"] = "DOM_LOADED";
  LoadStatus["PRE_INITIALIZE"] = "PRE_INITIALIZE";
  LoadStatus["LOADED"] = "LOADED";
})(LoadStatus || (LoadStatus = {}));
export var LoadType;
(function (LoadType) {
  LoadType["APP_LOAD"] = "APP_LOAD";
})(LoadType || (LoadType = {}));
