"use strict";

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

var _CustomScriptLoadingPlugin = require("../custom_plugins/CustomScriptLoadingPlugin");

var _utils = require("../utils");

const defaultScriptLoadingStrategy = 'defer';
const allowedScriptLoadingStrategies = ['blocking', 'defer', 'async', 'module'];

function isAllowedScriptLoadingStrategyUsed(scriptLoadingStategey) {
  return allowedScriptLoadingStrategies.includes(scriptLoadingStategey);
}

function getScriptLoadingStrategyForStringType(scriptLoadingStategey) {
  if (isAllowedScriptLoadingStrategyUsed(scriptLoadingStategey)) {
    return scriptLoadingStategey;
  }

  return defaultScriptLoadingStrategy;
}

function getScriptLoadingStrategyForObject(scriptLoadingStategey) {
  if (Object.keys(scriptLoadingStategey).length === 0) {
    return defaultScriptLoadingStrategy;
  }

  const isAllowedScriptLoadingStrategy = Object.keys(scriptLoadingStategey).every(key => isAllowedScriptLoadingStrategyUsed(key));

  if (isAllowedScriptLoadingStrategy) {
    return Object.assign({}, scriptLoadingStategey);
  }

  console.warn('un supported script loading strategy used', scriptLoadingStategey);
  return defaultScriptLoadingStrategy;
}

function getScriptLoadingStrategy(scriptLoadingStategey) {
  if ((0, _utils.getTypeOf)(scriptLoadingStategey) === 'string') {
    return {
      [getScriptLoadingStrategyForStringType(scriptLoadingStategey)]: [/.*/]
    };
  }

  if ((0, _utils.getTypeOf)(scriptLoadingStategey) === 'object') {
    return getScriptLoadingStrategyForObject(scriptLoadingStategey);
  }

  return {
    [defaultScriptLoadingStrategy]: [/.*/]
  };
}

function configCustomScriptLoadingStrategyPlugin(options) {
  const {
    customScriptLoadingStrategey
  } = options;

  if (customScriptLoadingStrategey) {
    const currentScriptLoadingStrategy = getScriptLoadingStrategy(customScriptLoadingStrategey.options);

    if ((0, _utils.getTypeOf)(currentScriptLoadingStrategy) === 'object') {
      return new _CustomScriptLoadingPlugin.CustomScriptLoadingStrategyPlugin({
        scriptLoadingStategey: currentScriptLoadingStrategy
      });
    } else {
      return null;
    }
  } else {
    return null;
  }
}