'use strict';

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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _warning = require('warning');

var _warning2 = _interopRequireDefault(_warning);

var _Pagination = require('./../Pagination');

var _Pagination2 = _interopRequireDefault(_Pagination);

var _TableBody = require('./src/TableBody');

var _TableBody2 = _interopRequireDefault(_TableBody);

var _TableFooter = require('./src/TableFooter');

var _TableFooter2 = _interopRequireDefault(_TableFooter);

var _TableHeader = require('./src/TableHeader');

var _TableHeader2 = _interopRequireDefault(_TableHeader);

var _TableRow = require('./src/TableRow');

var _TableRow2 = _interopRequireDefault(_TableRow);

var _TableRowColumn = require('./src/TableRowColumn');

var _TableRowColumn2 = _interopRequireDefault(_TableRowColumn);

var _Autocomplete = require('../Autocomplete');

var _Autocomplete2 = _interopRequireDefault(_Autocomplete);

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

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

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

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

var Table = function (_PureComponent) {
  _inherits(Table, _PureComponent);

  function Table() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, Table);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Table.__proto__ || Object.getPrototypeOf(Table)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
      sort: null,
      order: null,
      pageSelected: 0,
      pageCount: 1
    }, _this.onChangeOrder = function (_ref2) {
      var sort = _ref2.sort,
          order = _ref2.order;

      _this.reCalculateBodySelection = false;
      _this.setState({ sort: sort, order: order });
    }, _this.setPageCount = function (pageCount) {
      _this.setState({ pageCount: pageCount });
    }, _this.reCalculateBodySelection = true, _this.handleChange = function (values) {
      _this.setState({ filteredValues: values });
    }, _this.handlePageChange = function (item) {
      _this.setState({ pageSelected: item.selected });
    }, _this.bodyChildren = null, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(Table, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps() {
      this.reCalculateBodySelection = true;
    }
  }, {
    key: 'createTableHeader',
    value: function createTableHeader(base) {
      var _props = this.props,
          fixedHeader = _props.fixedHeader,
          selectable = _props.selectable,
          displayRowCheckbox = _props.displayRowCheckbox;

      if (base === undefined) {
        return {};
      }
      var nodeHeader = (0, _react.cloneElement)(base, {
        adjustForCheckbox: selectable && displayRowCheckbox,
        onChangeOrder: this.onChangeOrder,
        sortedField: this.state.sort,
        order: this.state.order,
        filtering: this.props.filtering
      });

      if (fixedHeader) {
        return {
          tableHeader: _react2.default.createElement(
            'table',
            { className: 'flive_table_table flive_table_table--header' },
            nodeHeader
          )
        };
      }

      return { inlineHeader: nodeHeader };
    }
  }, {
    key: 'createTableBody',
    value: function createTableBody(base) {
      var _props2 = this.props,
          displayRowCheckbox = _props2.displayRowCheckbox,
          selectable = _props2.selectable,
          multiSelectable = _props2.multiSelectable,
          filterOptions = _props2.filterOptions,
          filtering = _props2.filtering,
          paginate = _props2.paginate;
      var _state = this.state,
          sort = _state.sort,
          order = _state.order,
          pageSelected = _state.pageSelected,
          pageCount = _state.pageCount;

      this.bodyChildren = base && base.props.children;
      var filterOpts = void 0;
      if (filterOptions) {
        filterOpts = filterOptions;
      } else {
        filterOpts = this.state.filteredValues ? { filter: filtering, filterValues: this.state.filteredValues } : null;
      }

      return {
        tableBody: (0, _react.cloneElement)(base, {
          onChange: this.props.onChange,
          multiSelectable: multiSelectable,
          onCellClick: this.onCellClick,
          displayRowCheckbox: displayRowCheckbox,
          reCalculateSelection: this.reCalculateBodySelection,
          selectable: selectable || displayRowCheckbox || multiSelectable,
          sort: sort,
          order: order,
          paginate: paginate,
          filterOptions: filterOpts,
          pageSelected: pageSelected,
          pageCount: pageCount,
          setPageCount: this.setPageCount,
          handlePageChange: this.handlePageChange
        })
      };
    }
  }, {
    key: 'createTableFooter',
    value: function createTableFooter(base) {
      var _props3 = this.props,
          fixedFooter = _props3.fixedFooter,
          displayRowCheckbox = _props3.displayRowCheckbox,
          selectable = _props3.selectable;

      if (base === undefined) {
        return {};
      }
      var nodeFooter = (0, _react.cloneElement)(base, { adjustForCheckbox: selectable && displayRowCheckbox });
      if (fixedFooter) {
        return {
          tableFooter: _react2.default.createElement(
            'table',
            { className: 'flive_table_table flive_table_table--footer' },
            nodeFooter
          )
        };
      }
      return { inlineFooter: nodeFooter };
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _props4 = this.props,
          children = _props4.children,
          className = _props4.className,
          style = _props4.style,
          filtering = _props4.filtering;

      var _ref3 = _react.Children.toArray(children).reduce(function (resultObject, child) {
        if (!(0, _react.isValidElement)(child)) {
          return resultObject;
        }
        var componentName = child.type.componentName;

        switch (componentName) {
          case 'TableHeader':
            return _extends({}, _this2.createTableHeader(child), resultObject);
          case 'TableBody':
            return _extends({}, _this2.createTableBody(child), resultObject);
          case 'TableFooter':
            return _extends({}, _this2.createTableFooter(child), resultObject);
          default:
            (0, _warning2.default)(false, 'Flive-ui: Children of the Table component must be TableBody or TableHeader or TableFooter.\n              Nothing is rendered.');
            return resultObject;
        }
      }, {}) || {},
          tableHeader = _ref3.tableHeader,
          inlineHeader = _ref3.inlineHeader,
          tableBody = _ref3.tableBody,
          inlineFooter = _ref3.inlineFooter,
          tableFooter = _ref3.tableFooter;

      // If we could not find a table-header and a table-body, do not attempt to display anything.


      if (!(tableHeader || inlineHeader || tableBody) && !(inlineFooter || tableFooter || tableBody)) return null;
      return _react2.default.createElement(
        'div',
        { className: 'flive_table_table-wrapper' },
        filtering && _react2.default.createElement(
          'div',
          { className: 'flive_table_filter-wrapper' },
          'Search',
          _react2.default.createElement(_Autocomplete2.default, {
            placeholder: 'Enter ' + filtering + ' or part of it',
            noMatchLabel: 'No value matched',
            indexes: this.bodyChildren && _react.Children.toArray(this.bodyChildren).map(function (item) {
              return item.props.value[filtering] || '';
            }),
            onChange: this.handleChange,
            className: 'flive_table_filter',
            hideDropdown: true,
            ignoreCase: true
          })
        ),
        !tableHeader && !tableFooter ? _react2.default.createElement(
          'table',
          {
            className: (className ? className + ' ' : '') + 'flive_table_table',
            style: style
          },
          inlineHeader,
          inlineFooter,
          tableBody
        ) : _react2.default.createElement(
          'div',
          {
            style: style,
            className: (className ? className + ' ' : '') + 'flive_table_wrapper-fixed'
          },
          tableHeader,
          _react2.default.createElement(
            'div',
            { className: 'flive_table_wrapper-scroll' },
            _react2.default.createElement(
              'table',
              { className: 'flive_table_table flive_table_table--scrolled' },
              inlineHeader,
              tableBody,
              inlineFooter
            )
          ),
          tableFooter
        ),
        this.props.paginate && this.state.pageCount > 1 && _react2.default.createElement(_Pagination2.default, {
          pageCount: this.state.pageCount,
          pageRangeDisplayed: 10,
          marginPagesDisplayed: 1,
          forcePage: this.state.pageSelected,
          onPageChange: function onPageChange(item) {
            return _this2.handlePageChange(item);
          }
        })
      );
    }
  }]);

  return Table;
}(_react.PureComponent);

Table.propTypes = {
  /**
   * Children passed to table.
   */
  children: _propTypes2.default.node,
  /**
   * If true, the footer will appear fixed below the table.
   */
  fixedFooter: _propTypes2.default.bool,
  /**
   * If true, the header will appear fixed above the table.
   */
  fixedHeader: _propTypes2.default.bool,
  /**
   * If true, multiple table rows can be selected.
   * CTRL/CMD+Click and SHIFT+Click are valid actions.
   */
  multiSelectable: _propTypes2.default.bool,
  /**
   * Controls the display of the row checkbox.
   */
  displayRowCheckbox: _propTypes2.default.bool,
  /**
   * @ignore
   * Called when a row is selected. selectedRows is an
   * array of all row selections. IF all rows have been selected,
   * the string "all" will be returned instead to indicate that
   * all rows have been selected.
   */
  onChange: _propTypes2.default.func,
  /**
   * If true, table rows can be selected.
   * If multiple row selection is desired, enable multiSelectable.
   */
  selectable: _propTypes2.default.bool,
  className: _propTypes2.default.string,
  style: _propTypes2.default.object,
  filterOptions: _propTypes2.default.object,
  filtering: _propTypes2.default.string,
  paginate: _propTypes2.default.number
};
Table.defaultProps = {
  children: null,
  fixedFooter: false,
  fixedHeader: false,
  multiSelectable: false,
  displayRowCheckbox: false,
  onChange: null,
  selectable: false,
  className: null,
  style: null,
  filterOptions: null,
  filtering: null,
  paginate: null
};


Table.Body = _TableBody2.default;
Table.Footer = _TableFooter2.default;
Table.Header = _TableHeader2.default;
Table.Row = _TableRow2.default;
Table.RowColumn = _TableRowColumn2.default;

exports.default = Table;
module.exports = exports['default'];