"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _reactGridLayout = require("react-grid-layout");

var _react2 = require("@css-modules-theme/react");

var _Utils = _interopRequireDefault(require("../Utils"));

var _defaultLayoutConfiguration = require("./defaultLayoutConfiguration");

var _ItemsOrganizer = require("./ItemsOrganizer");

var _layoutUtils = require("./layoutUtils");

var _intersection = _interopRequireDefault(require("lodash/intersection"));

var _cloneDeep = _interopRequireDefault(require("lodash/cloneDeep"));

var _LayoutStyle = _interopRequireDefault(require("./LayoutStyle.scss"));

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

var ResponsiveLayout = (0, _reactGridLayout.WidthProvider)(_reactGridLayout.Responsive);

var CardsLayoutManager =
/*#__PURE__*/
function (_Component) {
  _inherits(CardsLayoutManager, _Component);

  function CardsLayoutManager(_props) {
    var _this;

    _classCallCheck(this, CardsLayoutManager);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(CardsLayoutManager).call(this, _props));

    _this.componentWillReceiveProps = function (props) {
      var layouts = (0, _layoutUtils.convertCardsToLayouts)(props.cardsConfiguration.cards, _this.breakpoints);

      _this.setState({
        layouts: layouts
      });
    };

    _this.onBreakpointChange = function (newBreakpoint) {
      console.log('breakpoint changing', _this.state.currentBreakpoint, '=>', newBreakpoint);

      _this.setState({
        currentBreakpoint: newBreakpoint
      });
    };

    _this.getCardIdsFromLayout = function (cards) {
      return Object.keys(cards);
    };

    var breakpoints = _defaultLayoutConfiguration.defaultLayoutConfiguration.breakpoints;
    _this.breakpoints = (0, _ItemsOrganizer.buildBreakpoints)(breakpoints);
    var breakpointCols = (0, _ItemsOrganizer.buildColMap)(breakpoints);
    _this.cols = breakpointCols; // how many columns per breakpoint

    _this.margins = _props.layoutConfiguration.cardMargin || _defaultLayoutConfiguration.defaultLayoutConfiguration.cardMargin;
    _this.padding = _props.layoutConfiguration.cardPadding || _defaultLayoutConfiguration.defaultLayoutConfiguration.cardPadding;
    _this.rowHeight = _props.layoutConfiguration.rowHeight || _defaultLayoutConfiguration.defaultLayoutConfiguration.rowHeight;
    _this.state = {
      layouts: (0, _layoutUtils.convertCardsToLayouts)(_props.cardsConfiguration.cards, _this.breakpoints)
    };
    return _this;
  }

  _createClass(CardsLayoutManager, [{
    key: "onDragStop",
    value: function onDragStop(curLayout) {
      var allLayouts = this.state.layouts;
      if (!this.state.currentBreakpoint) console.error("on drag stop- currentBreakpoint= ", this.state.currentBreakpoint);
      allLayouts[this.state.currentBreakpoint] = curLayout;
      var cards = (0, _cloneDeep["default"])(this.props.cardsConfiguration.cards);
      (0, _layoutUtils.convertLayoutToCards)(this.state.currentBreakpoint, curLayout, cards);
      this.props.onLayoutChange(cards);
      this.setState({
        layouts: allLayouts
      });
    }
  }, {
    key: "getChildrenWithKeys",
    value: function getChildrenWithKeys(cardsOrder) {
      if (!cardsOrder) {
        return null;
      }

      var wrappedChildren = [];

      _react["default"].Children.map(this.props.children, function (child) {
        if (cardsOrder.indexOf(child.props.configId) > -1) {
          return wrappedChildren.push(_react["default"].createElement("div", {
            key: child.props.configId
          }, child));
        }

        return null;
      });

      var filtered = wrappedChildren.filter(function (component) {
        return component !== null;
      });
      return filtered;
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
          theme = _this$props.theme,
          themeProps = _this$props.themeProps;
      var themingProperties = (0, _Utils["default"])(theme, themeProps);
      var themeStyles = (0, _react2.composeThemeFromProps)(_LayoutStyle["default"], themingProperties, {
        compose: 'Merge'
      });
      var layouts;
      var cards = this.props.cardsConfiguration.cards;
      if (!cards) return null;
      var childrenWithKeys = null;

      if (this.props.layoutConfiguration.draggable) {
        /* this is a layout where a user can move cards anywhere he wants */
        var cardIds = this.getCardIdsFromLayout(cards);
        childrenWithKeys = this.getChildrenWithKeys(cardIds);
        layouts = this.state.layouts;
      } else {
        /*
            This is a predefined layout, use our algorithm to organize the children
            left to right, top to bottom, based on cardsOrder array
        */
        var cardsOrder = this.props.cardsConfiguration.cardsOrder;
        if (cardsOrder === undefined && cardsOrder.length === 0) return null;
        childrenWithKeys = this.getChildrenWithKeys(cardsOrder); // Revise Cards Order to include only children

        var childrenKeys = childrenWithKeys.map(function (child) {
          return child.key;
        });
        var revisedCardsOrder = (0, _intersection["default"])(cardsOrder, childrenKeys);
        layouts = (0, _ItemsOrganizer.extractLayout)(cards, revisedCardsOrder, _defaultLayoutConfiguration.defaultLayoutConfiguration.breakpoints);
      }

      if (!layouts) {
        return _react["default"].createElement("div", {
          className: themeStyles.emptyLayout
        }, _react["default"].createElement("div", {
          className: themeStyles.emptyLayoutIcon
        }), _react["default"].createElement("div", null, "NO DATA"));
      }

      var isDraggable = this.props.layoutConfiguration.draggable;
      var classDraggable = isDraggable ? "draggable" : "";
      return _react["default"].createElement(ResponsiveLayout, {
        className: "".concat(themeStyles.cardsLayoutContainer, " ").concat(themeStyles.classDraggable),
        layouts: layouts,
        breakpoints: this.breakpoints,
        cols: this.cols,
        isResizable: false,
        isDraggable: isDraggable // this is dynamic
        ,
        rowHeight: this.rowHeight,
        margin: this.margins,
        containerPadding: this.padding,
        draggableHandle: ".header, .card",
        draggableCancel: ".actions, .cardContent, .cardContentNoHeader, .title",
        onBreakpointChange: this.onBreakpointChange,
        onDragStop: this.onDragStop.bind(this),
        compactType: "vertical"
      }, childrenWithKeys);
    }
  }]);

  return CardsLayoutManager;
}(_react.Component);

exports["default"] = CardsLayoutManager;
CardsLayoutManager.propTypes = {
  children: _propTypes["default"].arrayOf(_propTypes["default"].shape({
    configId: _propTypes["default"].string,
    title: _propTypes["default"].string,
    actions: _propTypes["default"].arrayOf(_propTypes["default"].shape({
      id: _propTypes["default"].string,
      displayName: _propTypes["default"].string
    }))
  })),
  layoutConfiguration: _propTypes["default"].shape({
    draggable: _propTypes["default"].bool,
    rowHeight: _propTypes["default"].number,
    cardMargin: _propTypes["default"].arrayOf(_propTypes["default"].number),
    cardPadding: _propTypes["default"].arrayOf(_propTypes["default"].number)
  }),
  cardsConfiguration: _propTypes["default"].instanceOf(Object),
  onLayoutChange: _propTypes["default"].instanceOf(Object),
  cardsOrder: _propTypes["default"].instanceOf(Array),
  themeProps: _propTypes["default"].shape({
    compose: _propTypes["default"].string,
    prefix: _propTypes["default"].string
  }),
  theme: _propTypes["default"].instanceOf(Object)
};
CardsLayoutManager.defaultProps = {
  layoutConfiguration: [],
  cardsConfiguration: [],
  themeProps: {
    compose: 'merge',
    prefix: 'configurableInteractiveLayout-'
  }
};