"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.prescanModel = prescanModel;
exports._useUpdatedUserPrescan = _useUpdatedUserPrescan;
exports.userInstalledHome = userInstalledHome;
exports.init = exports.preload = exports.registrar = exports.pluginRoot = void 0;

var _debug = _interopRequireDefault(require("debug"));

var _preloader = _interopRequireDefault(require("./preloader"));

var _resolver = require("./resolver");

var _prescan = require("./prescan");

var _userdata = require("../core/userdata");

var _capabilities = require("../core/capabilities");

var _commandTree = require("../core/command-tree");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/*
 * Copyright 2017-2019 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());
  });
};

const debug = (0, _debug.default)('core/plugins');
debug('loading');
debug('modules loaded');
const pluginRoot = '../../../../plugins';
/**
 * This is the registrar for plugins used at runtime (i.e. "live, not
 * scanning"). This is not related to the prescan computation.
 *
 */

exports.pluginRoot = pluginRoot;
const registrar = {};
/**
 * When in "live, not scanning" mode, this state will store the result
 * of a previous plugin scan
 *
 */

exports.registrar = registrar;
let basePrescan; // without any user-installed plugins

let prescan;

try {
  prescan = require('@kui-shell/prescan.json'); // the result of unify(basePrescan, userPrescan)
} catch (err) {
  debug(err);
}

function prescanModel() {
  return prescan;
}
/**
 * For internal use only: set the prescan model
 *
 */


function _useUpdatedUserPrescan(userPrescan) {
  debug('useUpdatedUserPrescan', userPrescan, basePrescan);
  prescan = (0, _prescan.unify)(basePrescan, userPrescan);
  (0, _commandTree.setPluginResolver)((0, _resolver.makeResolver)(prescan, registrar));
}

const preload = () => {
  return (0, _preloader.default)(prescan);
};
/**
 * @return the home directory for user-installed plugins. All
 * artifacts related to user-installed plugins will be stored within
 * this directory.
 *
 */


exports.preload = preload;

function userInstalledHome() {
  return __awaiter(this, void 0, void 0, function* () {
    const {
      join
    } = yield Promise.resolve().then(() => require('path'));
    const rootDir = (0, _userdata.userDataDir)();
    return join(rootDir, 'plugins');
  });
}
/**
 * Load the prescan model, in preparation for loading the shell
 *
 * @return truthy value if we indeed did the initialization
 */


const init = () => __awaiter(void 0, void 0, void 0, function* () {
  debug('init');

  if (basePrescan) {
    return false;
  } // pre-installed plugins


  basePrescan = prescan;

  if ((0, _capabilities.isHeadless)() && prescan) {
    try {
      const [{
        existsSync
      }, {
        join
      }] = yield Promise.all([Promise.resolve().then(() => require('fs')), Promise.resolve().then(() => require('path'))]);
      const userPath = join(yield userInstalledHome(), 'node_modules/@kui-shell/prescan.json');

      if (existsSync(userPath)) {
        const userInstalledPrescan = yield Promise.resolve().then(() => require(`${userPath}`)); // merge builtin plugins with user-installed plugins

        prescan = (0, _prescan.unify)(prescan, userInstalledPrescan); // debug('prescan', prescan)
      }

      debug('user-installed prescan loaded', prescan);
    } catch (err) {
      console.error('error loading user-installed prescan', err);
    }
  }
  /* const { default: eventChannelUnsafe } = await import('../core/events')
  eventChannelUnsafe.on('/plugin/compile/request', async (pluginToBeRemoved?: string) => {
    const { compileUserInstalled } = await import('./assembler')
    compileUserInstalled(pluginToBeRemoved)
  }) */


  (0, _commandTree.setPluginResolver)((0, _resolver.makeResolver)(prescan, registrar));
  debug('init done');
  return true;
});

exports.init = init;
debug('done loading');