"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.WidgetAfterSaveMethods = exports.SaveTypes = void 0;
exports.getComponent = getComponent;
exports.getConf = getConf;
exports.getCustomApplicationConfiguration = void 0;
exports.getQueryParams = getQueryParams;
exports.init = init;
exports.isProduction = isProduction;
exports.setConf = setConf;
exports.setConfiguration = setConfiguration;
exports.setCustomApplicationConfiguration = void 0;
var _get = _interopRequireDefault(require("lodash/get"));
var _merge = _interopRequireDefault(require("lodash/merge"));
var _set = _interopRequireDefault(require("lodash/set"));
var _Api = _interopRequireDefault(require("../Framework/Api"));
var _hyphenatedDe = _interopRequireDefault(require("hyphenated-de"));
var _Reducer = require("./Reducers/Configurator/Reducer");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
var DEVELOPMENT_HOST_INT = 'http://int.configuratorware-dev.local';

// eslint-disable-next-line no-unused-vars
var DEVELOPMENT_HOST_LOCAL = 'http://localhost:10030';
var hostsByNodeEnv = {
  production: '',
  development: DEVELOPMENT_HOST_LOCAL,
  test: ''
};
var resourceUrlsByNodeEnv = {
  production: '',
  development: DEVELOPMENT_HOST_INT,
  test: ''
};
var host = hostsByNodeEnv[process.env.NODE_ENV];
var resourcesURL = resourceUrlsByNodeEnv[process.env.NODE_ENV];
var network = {
  host: host,
  baseURL: "".concat(host, "/frontendapi/"),
  resourcesURL: resourcesURL,
  timeout: 60000
};
var SaveTypes = exports.SaveTypes = {
  USER: 'user',
  DEFAULTOPTIONS: 'defaultoptions',
  INSPIRATION: 'inspiration',
  CART: 'cart',
  MAIL: 'mail',
  SHARE: 'share',
  LANGUAGESWITCH: 'languageswitch',
  CHANNELSWITCH: 'channelswitch',
  PRINT: 'print',
  DESIGNTEMPLATE: 'designtemplate',
  OFFERREQUEST: 'offer_request',
  WIDGET: 'widget'
};
var WidgetAfterSaveMethods = exports.WidgetAfterSaveMethods = {
  OpenNewWindow: 'openNewWindow',
  PostMessage: 'postMessage'
};
var applicationConfiguration = {
  network: network,
  // the default language code (format: de-DE, en-GB, etc.), use false to select the browser language
  language: false,
  // the available locales
  locales: [{
    code: 'de_DE',
    preferred: true
  }, {
    code: 'en_GB'
  }],
  // although our locale is en-GB we use American English patterns for hyphenation
  // to reduce bundle size because they are already included in hyphenated/react-hyphen
  hyphenations: {
    'de-DE': _hyphenatedDe["default"],
    'en-GB': 'en-US'
  },
  // array of configuration save types
  saveTypes: SaveTypes,
  // show custom title input before saving the configuration
  editCustomTitleBeforeSave: false,
  // default: false

  // which types need a custom title before saving?
  customTitleSaveTypes: [SaveTypes.DESIGNTEMPLATE, SaveTypes.INSPIRATION],
  // set true to load available variants before loading the configuration
  loadVariantsFirst: false,
  // default: false

  // set true to load
  loadInspirations: false,
  // default: false

  // set true to open the first optionclassification instead of the "start here" text
  showInitialOptionclassification: false,
  // default: false

  // show the "start here" animation
  showStartHere: true,
  // show the "add to cart" button by default
  showAddToCartButton: true,
  // set true to run server-side validation before addToCart
  validateBeforeCTA: true,
  // set false to decide by screen orientation, or can be fixed 'left' or 'bottom'
  dock: false,
  // set true to display the selected option for each optionclassification
  displaySwitchedOptions: false,
  // default: false

  // set true to check the optionclassification immediately after selected
  checkOptionclassificationOnSelect: false,
  // which method is used for addToCart? default: postMessage
  // when it is set to 'functionCall' it calls window.parent.addToCart(configuration.code)
  addToCartMethod: 'postMessage',
  // use carousel for optionclassification list
  optionclassificationCarousel: true,
  // set true to disable beforeunload warning
  disableBeforeunloadWarning: false,
  // set true to hide optionlist when user clicks somewhere else
  hideOptionListOnAwayClick: true,
  // set true to force the option details dialog shown with an image
  optionDetailsWithImage: false,
  // set true to disable optionlist moving
  fixedOptionlist: false,
  //set true to show accept design checkbox approval
  displayAcceptDesign: true,
  // available tools in the toolbar
  availableTools: {
    fastConfiguration: false,
    save: true,
    load: true,
    share: true,
    print: true
  },
  // relative position of the option list dialog
  // [
  //   [<dialogSideH{left|center|right}>, <relToSideH{left|center|right}>],
  //   [<dialogSideV{top|center|bottom}>, <relToSideV{top|center|bottom}>]
  // ]
  optionlistDialogPositioning: {
    left: [['left', 'right'], ['top', 'top']],
    bottom: [['center', 'center'], ['bottom', 'top']]
  },
  // override this to set a default item identifier to load if not defined in the route
  defaultLoadIdentifier: false,
  // should the option list be fixed to the left side, or it can open up above the selected option classification
  optionListFixedToLeft: true,
  // the components used in the Screen (override any component in custom project)
  components: {},
  // the containers used in the Screen (override any container in custom project)
  containers: {},
  // load the available configuration modes (might be set to false in older configurators)
  loadConfigurationModes: true,
  // if set to false only the amount for the currently selected variant can be selected
  // when switching the variant the selected amount is transferred to the newly selected variant
  restrictAmountselectionToSelectedVariant: false,
  displayColorAmountWarnings: true,
  displayEditorRulers: true,
  // default options for opening the configurator (eg. after saved from the calculation widget)
  openConfigurator: {
    method: WidgetAfterSaveMethods.OpenNewWindow
    // when the PostMessage mode is used the targetOrigin can be specified, otherwise '*' will be used
  },

  visualization: {
    useVisualizationScript: {
      src: '' // source of the visualization script in the public folder, e.g. 'visualization.js'
    },

    designAreaHighlightBackgroundColor: 'transparent',
    options: {
      // when zoom = 1 use NearestFilter (for sharper product image)
      sharperFullView: false,
      // upscale or downscale the product image to fit 2048 x 2048
      // Warning! not recommended, use better image resources instead
      optimizeProductImage: false
    },
    options3D: {
      // create a ground to show a shadow under the model
      useShadowGround: true,
      // remove the shadow ground for screenshots
      removeGroundForScreenshot: true,
      // use an environment map
      useEnvironmentMap: true,
      // use programmatically generated baked shadow (instead of directional light shadow)
      useBakedShadows: false,
      // baked shadow parameters (for all available see redhotmagma-visualization/src/Three/Three3DScene.js)
      bakedShadow: {
        blurRadius: 6,
        shadowOpacity: 0.8
      }
    }
  },
  designer: {
    dpi: 300,
    // the default canvas dpi as project specific option
    maxColorAmount: 10,
    // the default max number of colors in the colorizing feature
    allowedImageUploadFormats: 'jpg,jpeg,svg,png,pdf,bmp,tif,tiff,eps,ai,gif',
    // the image formats users can upload to designareas / designer items
    includeMetricContentSize: false // set true to include the metric content size in the design data
  },

  vectorizeImageQuality: 45000,
  renderPreviewImagesForCheckout: true,
  // automatically show the vectorization preview in colorizing step
  autoPreviewVectorization: true,
  // switch to the previously selected view when selecting a component that has no view specified
  switchViewOnComponentSelection: true,
  parameterParser: function parameterParser(name, value) {
    return value;
  }
};
function preventLeavingPage() {
  if (process.env.NODE_ENV === 'production' && !getConf('adminMode')) {
    // registering beforeunload event
    // in dev mode it prevents the hot reloading, use only in production mode
    if (!getConf('disableBeforeunloadWarning')) {
      window.addEventListener('beforeunload', function (e) {
        // disableBeforeunloadWarning is checked again, so that it can be disabled during runtime (after mount)
        if (getConf('disableBeforeunloadWarning')) {
          return false;
        } else {
          var confirmationMessage = 'Are you sure?'; // this message will not be shown
          e.returnValue = confirmationMessage; // Gecko, Trident, Chrome 34+
          return confirmationMessage; // Gecko, WebKit, Chrome <34
        }
      });
    }
  }
}

function init() {
  var externalConfig = window.externalConfiguration;
  if (externalConfig) {
    applicationConfiguration = (0, _merge["default"])(applicationConfiguration, externalConfig);
  }
  applicationConfiguration = (0, _merge["default"])(applicationConfiguration, getQueryParams(applicationConfiguration.parameterParser));
  _Api["default"].init(applicationConfiguration.network);
  preventLeavingPage();
  return applicationConfiguration;
}
function getQueryParams() {
  var parameterParser = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function (_name, value) {
    return value;
  };
  var query = new URLSearchParams(location.search);
  var queryConf = {};

  // if the language is in the params, set it from there
  if (query.has('_language')) {
    queryConf.language = query.get('_language').replace('_', '-');
  }
  if (query.has('_channel')) {
    var channel = query.get('_channel');
    queryConf.channel = channel;
    _Api["default"].setChannel(channel);
  }

  // hide variants selection
  if (query.has('_hidevariantselection') && query.get('_hidevariantselection') === 'true') {
    queryConf.loadVariantsFirst = false;
  }

  // admin modes
  if (query.has('_adminmode')) {
    queryConf.adminMode = query.get('_adminmode');
  }
  if (query.has('_adminapitoken')) {
    queryConf.adminApiToken = query.get('_adminapitoken');
  }

  // add reference to parent when saving (normally used when coming back from the cart)
  if (query.has('_addparentcodeonsave')) {
    queryConf.addParentCodeOnSave = true;
  }
  if (query.has('_share_url')) {
    _Api["default"].setGETParameter('_share_url', encodeURIComponent(query.get('_share_url')));
  }
  if (query.has('_designerPreSelection')) {
    try {
      queryConf.designerPreSelection = JSON.parse(query.get('_designerPreSelection'));
    } catch (e) {
      // eslint-disable-next-line no-console
      console.error('_designerPreSelection parse error', e);
    }
  }
  if (query.has('_frombasket')) {
    queryConf.fromBasket = query.get('_frombasket') === '1';
  }
  if (query.has('_admin_mode_hash')) {
    _Api["default"].setGETParameter('_admin_mode', query.get('_admin_mode_hash'));
  }
  if (query.has('_client')) {
    _Api["default"].setGETParameter('_client', query.get('_client'));
  }
  if (query.has('_display_net_prices') && query.get('_display_net_prices') === '1') {
    queryConf.displayNetPrices = true;
    _Api["default"].setGETParameter('_display_net_prices', query.get('_display_net_prices'));
  }
  if (query.has('_configuration_mode')) {
    queryConf.configurationMode = query.get('_configuration_mode');
  }
  if (query.has('_cta_element')) {
    _Api["default"].setGETParameter('_cta_element', query.get('_cta_element'));
  }
  if (query.has('_hide_prices')) {
    _Api["default"].setGETParameter('_hide_prices', query.get('_hide_prices'));
  }
  if (query.has('_switch_options')) {
    var optionsToSwitchJSON = query.get('_switch_options');
    try {
      queryConf.selectOptions = JSON.parse(optionsToSwitchJSON);
    } catch (e) {
      // eslint-disable-next-line no-console
      console.error('Wrong JSON provided for _switch_options:', optionsToSwitchJSON);
    }
  }
  if (query.has('_country')) {
    var country = query.get('_country');
    if (country && country.length === 2) {
      _Api["default"].setGETParameter('_country', country);
    }
  }

  // Forward all query parameters starting with "_" to Api.setGETParameter
  var _iterator = _createForOfIteratorHelper(query.entries()),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var _step$value = _slicedToArray(_step.value, 2),
        name = _step$value[0],
        value = _step$value[1];
      if (name.startsWith('_')) {
        _Api["default"].setGETParameter(name, parameterParser(name, value));
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return queryConf;
}
function setConfiguration(customApplicationConfiguration) {
  applicationConfiguration = (0, _merge["default"])(applicationConfiguration, customApplicationConfiguration, getQueryParams());

  // if there is a config for network Api instance defaults must be updated
  if (applicationConfiguration.network) {
    _Api["default"].init(applicationConfiguration.network);
  }

  // set possible sub reducers and state change reducers
  if ((0, _get["default"])(applicationConfiguration, 'reducers.configurator')) {
    var _applicationConfigura = applicationConfiguration.reducers.configurator,
      subReducers = _applicationConfigura.subReducers,
      stateChangeReducers = _applicationConfigura.stateChangeReducers;
    (0, _Reducer.setSubReducers)(subReducers);
    (0, _Reducer.setStateChangeReducers)(stateChangeReducers);
  }
}

// backward compatibility alias
var setCustomApplicationConfiguration = exports.setCustomApplicationConfiguration = setConfiguration;
function getConf(path, dflt) {
  return path ? (0, _get["default"])(applicationConfiguration, path, dflt) : applicationConfiguration;
}
function setConf(path, value) {
  (0, _set["default"])(applicationConfiguration, path, value);
}

// backward compatibility alias
var getCustomApplicationConfiguration = exports.getCustomApplicationConfiguration = getConf;
function getComponent(name) {
  return getConf("components.".concat(name));
}
function isProduction() {
  return process.env.NODE_ENV === 'production';
}