"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = _default;

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

var _store = _interopRequireDefault(require("../main/store"));

var _elementMimic = _interopRequireDefault(require("./element-mimic"));

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.
 */
const debug = (0, _debug.default)('core/util/mimic-dom');
debug('loading');

/**
 * Create structures to mimic having a head
 *
 */
function _default() {
  debug('mimicDom');
  global.window = {
    navigator: {
      userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:74.0) Gecko/20100101 Firefox/74.0'
    }
  };

  try {
    global.localStorage = (0, _store.default)();
    global.sessionStorage = (0, _store.default)();
    debug('successfully initialized persistent localStorage');
  } catch (err) {
    debug('error initializing persistent localStorage', err);
    const _localStorage = {};
    const _sessionStorage = {};
    global.localStorage = {
      setItem: (k, v) => {
        _localStorage[k] = v;
        return v;
      },
      getItem: k => _localStorage[k] || null
    };
    global.sessionStorage = {
      setItem: (k, v) => {
        _sessionStorage[k] = v;
        return v;
      },
      getItem: k => _sessionStorage[k] || null
    };
  } finally {
    global.window.localStorage = localStorage;
    global.window.sessionStorage = sessionStorage;
  }

  window.addEventListener = () => true;

  const dom0 = () => {
    return new _elementMimic.default();
  };

  global.document = {
    body: dom0(),
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    getElementById: id => dom0(),
    createElement: tag => {
      const element = dom0();
      element.nodeType = tag;

      if (tag === 'table') {
        element.rows = [];
      }

      return element;
    },
    addEventListener: () => true,
    createTextNode: text => {
      const element = dom0();
      element.innerText = text;
      return element;
    },
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    querySelector: selector => {
      return dom0();
    }
  };
  debug('mimicDom done');
}