"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getModelInternal = getModelInternal;
exports.getModel = getModel;
exports.init = init;
exports.initIfNeeded = initIfNeeded;
exports.CommandModelImpl = void 0;

/*
 * Copyright 2017-19 IBM Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var __awaiter = void 0 && (void 0).__awaiter || function (thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function (resolve) {
      resolve(value);
    });
  }

  return new (P || (P = Promise))(function (resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }

    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }

    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }

    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
/**
 * The internal implementation of the command tree
 *
 */


class CommandModelImpl {
  constructor() {
    /** root of the tree model */
    this._root = this.newTree();
    /** map from command name to disambiguations */

    this._disambiguator = {};
    /** handlers for command not found */

    this._catchalls = [];
  }

  get root() {
    return this._root;
  }

  get disambiguator() {
    return this._disambiguator;
  }

  get catchalls() {
    return this._catchalls;
  }
  /**
   * Look up a command handler for the given `argv`. This is the main
   * Read part of a REPL.
   *
   */


  read(argv, execOptions, tryCatchalls = true) {
    return __awaiter(this, void 0, void 0, function* () {
      const {
        read: readImpl
      } = yield Promise.resolve().then(() => require('../core/command-tree'));
      return readImpl(this.root, argv, undefined, execOptions, tryCatchalls);
    });
  }
  /**
   * Call the given callback function `fn` for each node in the command tree
   *
   */


  forEachNode(fn) {
    const iter = root => {
      if (root) {
        fn(root);

        if (root.children) {
          for (const cmd in root.children) {
            iter(root.children[cmd]);
          }
        }
      }
    };

    iter(this.root);
  }

  newTree() {
    return {
      $: undefined,
      key: '/',
      route: '/',
      children: {},
      parent: undefined
    };
  }

}

exports.CommandModelImpl = CommandModelImpl;

function isWindowWithModel(win) {
  return win && win._kuiCommandModel !== undefined;
}
/**
 * Global state representing the current tree of registered commands
 *
 */


let theCommandModel;
/**
 * @return the command tree model for internal consumption within this
 * file
 *
 */

function getModelInternal() {
  return typeof window !== 'undefined' && isWindowWithModel(window) && window._kuiCommandModel || theCommandModel;
}
/**
 * @return the command tree model for public consumption within the
 * rest of @kui-shell/core. For the model we present to plugins, see
 * `ImplForPlugins` in command-tree.ts
 *
 */


function getModel() {
  return getModelInternal();
}

function init() {
  theCommandModel = new CommandModelImpl();

  if (typeof window !== 'undefined') {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    ;
    window._kuiCommandModel = theCommandModel;
  }
}

function initIfNeeded() {
  if (!theCommandModel) {
    init();
  }
}