"use strict";

function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = designViewReducer;
var _Actions = require("./Actions");
var _find = _interopRequireDefault(require("lodash/find"));
var _get = _interopRequireDefault(require("lodash/get"));
var configuratorActionTypes = _interopRequireWildcard(require("../Configurator/Actions"));
var _Transformers = require("./Transformers");
var _Selectors = require("../ConfigurationMode/Selectors");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
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 _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
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 orderDesignAreasBySize = function orderDesignAreasBySize(designAreas) {
  return designAreas && _toConsumableArray(designAreas).sort(_Transformers.compareDesignAreasBySize);
};
var prepareDesignViews = function prepareDesignViews(designViews) {
  return designViews.map(function (designView) {
    return _objectSpread(_objectSpread({}, designView), {}, {
      designAreas: orderDesignAreasBySize(designView.designAreas)
    });
  });
};
var initialState = {
  designViews: [],
  selectedDesignView: {},
  autogeneratedDesignViews: [],
  viewThumbnailImages: []
};
function designViewReducer() {
  var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState;
  var action = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  switch (action.type) {
    case _Actions.actionTypes.SELECT_DESIGN_VIEW:
      {
        var designViewIdentifier = action.designViewIdentifier;
        var designView = (0, _find["default"])(state.designViews, {
          identifier: designViewIdentifier
        });
        return _objectSpread(_objectSpread({}, state), {}, {
          selectedDesignView: designView
        });
      }
    case configuratorActionTypes.RECEIVE_DESIGNER_DATA:
      {
        var autogeneratedDesignViews = state.autogeneratedDesignViews;
        var designViews = action.data.designViews;
        if (!designViews || !designViews.length) {
          // if there are no design views defined, use the autogenerated ones as fallback
          // use-case: missing visual maintenance setup for layer type visualization (designer only)
          if (autogeneratedDesignViews.length) {
            return _objectSpread(_objectSpread({}, state), {}, {
              designViews: autogeneratedDesignViews
            });
          }
          return state;
        }
        if (autogeneratedDesignViews.length) {
          // if the design views are already defined by the viewImages they need to be merged
          var updatedDesignViews = autogeneratedDesignViews.map(function (designView) {
            return _objectSpread(_objectSpread({}, designViews.find(function (_ref) {
              var identifier = _ref.identifier;
              return designView.identifier === identifier;
            })), designView);
          });
          return _objectSpread(_objectSpread({}, state), {}, {
            designViews: prepareDesignViews(updatedDesignViews),
            selectedDesignView: {}
          });
        }
        return _objectSpread(_objectSpread({}, state), {}, {
          designViews: prepareDesignViews(designViews),
          selectedDesignView: {}
        });
      }
    case configuratorActionTypes.RECEIVE_CONFIGURATION:
      {
        var viewImages = (0, _get["default"])(action, 'data.visualizationData.viewImages');
        var viewIdentifiers = viewImages && Object.keys(viewImages);
        if (viewIdentifiers && viewIdentifiers.length) {
          var viewThumbnailImages = (0, _get["default"])(action, 'data.visualizationData.viewThumbImages');
          var _autogeneratedDesignViews = viewIdentifiers.map(function (identifier) {
            return {
              identifier: identifier
            };
          });
          // if designer mode is enabled, the design views are loaded in a separate action
          // so it's not stored directly as designViews
          if ((0, _Selectors.getConfigurationModes)((0, _get["default"])(action, 'data.item')).designer) {
            return _objectSpread(_objectSpread({}, state), {}, {
              designViews: [],
              selectedDesignView: {},
              autogeneratedDesignViews: _autogeneratedDesignViews,
              viewThumbnailImages: viewThumbnailImages
            });
          }
          // otherwise designViews are not expected from other actions
          // so the autogenerated ones should be used as fallback
          var selectedDesignView = _autogeneratedDesignViews[0];
          return _objectSpread(_objectSpread({}, state), {}, {
            designViews: _autogeneratedDesignViews,
            selectedDesignView: selectedDesignView,
            autogeneratedDesignViews: _autogeneratedDesignViews,
            viewThumbnailImages: viewThumbnailImages
          });
        }
        // receiving a new configuration should always reset the design view state to not mix them up
        return _objectSpread(_objectSpread({}, state), {}, {
          designViews: [],
          selectedDesignView: {},
          autogeneratedDesignViews: [],
          viewThumbnailImages: []
        });
      }
  }
  return state;
}