"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.preinit = exports.init = void 0;

var _client = require("./client");

var _events = _interopRequireDefault(require("../../core/events"));

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

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

/**
 * We don't (at least not for now) want to support drag and drop at the global scope
 *
 */
const nope = event => {
  event.preventDefault();
  return false;
};

const disableDragAndDrop = () => {
  // debug('disableDragAndDrop')
  document.addEventListener('dragover', nope, false);
  document.addEventListener('drop', nope, false);
};
/**
 * When commands are executed, the command resolver will use a
 * fallback prefix. This routine tries to discover, from the
 * environment, what the default fallback prefix should be.
 *
 */


function setDefaultCommandContext() {
  return __awaiter(this, void 0, void 0, function* () {
    const {
      extractSearchKey
    } = yield Promise.resolve().then(() => require('../util/search'));
    const contextString = process.env.KUI_CONTEXT || typeof window !== 'undefined' && window.location && window.location.search && extractSearchKey('command-context');

    if (contextString) {
      try {
        const context = JSON.parse(contextString);
        const {
          setDefaultCommandContext: setDefault
        } = yield Promise.resolve().then(() => require('../../commands/context'));
        setDefault(context);
        return;
      } catch (err) {
        console.error('Error parsing KUI_CONTEXT', err);
      }
    }
  });
}

const init = () => __awaiter(void 0, void 0, void 0, function* () {
  // debug('init')
  const waitForThese = []; // debug('window init')

  _events.default.emit('/window/init');

  disableDragAndDrop();
  waitForThese.push(setDefaultCommandContext());
  window.addEventListener('beforeunload', () => {
    _events.default.emit('/window/reload');
  });
  waitForThese.push(Promise.resolve().then(() => require('../themes/init')).then(_ => _.default()));
  yield Promise.all(waitForThese); // debug('init done')
});

exports.init = init;

const preinit = inSandbox => __awaiter(void 0, void 0, void 0, function* () {
  // debug('preinit')
  let prefs = {};
  /** add os-xxxx to the body's classname, to allow for os-specific styling, if needed */

  document.body.classList.add(`os-${process.platform}`);

  if (!inSandbox && !(0, _client.inBrowser)()) {
    // Notes: sequester the electron bits into their own chunk, to
    // prevent webpack from bunching code that has an
    // `import('electron')` into the main bundle
    prefs = yield Promise.resolve().then(() => require('./init-electron')).then(_ => _.preinit());
  }

  return prefs;
});

exports.preinit = preinit;