'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 _getClassName2 = require('babel-plugin-react-css-modules/dist/browser/getClassName');

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _isEqual2 = require('lodash/isEqual');

var _isEqual3 = _interopRequireDefault(_isEqual2);

var _reactSticky = require('react-sticky');

var _omit = require('lodash/omit');

var _omit2 = _interopRequireDefault(_omit);

var _Section = require('../../Section');

var _Section2 = _interopRequireDefault(_Section);

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

var _styleModuleImportMap = {
  './tabs-container.scss': {
    'base': 'flive_tabs-container_base',
    'primary': 'flive_tabs-container_primary',
    'band': 'flive_tabs-container_band flive_tabs-container_base',
    'column': 'flive_tabs-container_column',
    'row': 'flive_tabs-container_row'
  }
};

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

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; }

// eslint-disable-line no-unused-vars

var Column = _Section2.default.Column;


var propTypes = {
  children: _propTypes2.default.node,
  scrollSpy: _propTypes2.default.object,
  sticky: _propTypes2.default.object,
  withHashTag: _propTypes2.default.bool,
  tabDirection: _propTypes2.default.oneOf(['column', 'row'])
};

var defaultProps = {
  children: undefined,
  scrollSpy: null,
  sticky: null,
  withHashTag: false,
  tabDirection: 'column'
};

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

  function TabsContainer() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, TabsContainer);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = TabsContainer.__proto__ || Object.getPrototypeOf(TabsContainer)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
      selectedIndex: 0,
      targetItems: [],
      inViewState: []
    }, _this.targetChildren = {}, _this.timer = null, _this.onTabsChange = function (selectedIndex) {
      _this.setState({
        selectedIndex: selectedIndex
      });
    }, _this._getElemsViewState = function () {
      var inView = [];
      var outView = [];
      var viewStatusList = [];
      var targetItems = _this.state.targetItems;

      var hasInViewAlready = false;

      for (var i = 0, max = targetItems.length; i < max; i += 1) {
        if (!_this.targetChildren[targetItems[i]]) {
          _this.targetChildren[targetItems[i]] = document.getElementById(targetItems[i]);
        }
        var currentContent = _this.targetChildren[targetItems[i]];
        var isInView = hasInViewAlready ? false : _this._isInView(currentContent, i);
        if (isInView) {
          hasInViewAlready = true;
          inView.push(currentContent);
        } else {
          outView.push(currentContent);
        }
        viewStatusList.push(isInView);
      }

      return { inView: inView, outView: outView, viewStatusList: viewStatusList };
    }, _this._isInView = function (el) {
      if (!el) return false;

      var _ref2 = _this.props.scrollSpy || {},
          _ref2$topOffset = _ref2.topOffset,
          topOffset = _ref2$topOffset === undefined ? 0 : _ref2$topOffset;

      var _el$getBoundingClient = el.getBoundingClientRect(),
          top = _el$getBoundingClient.top,
          height = _el$getBoundingClient.height;

      return top + height + topOffset > 0 || top > 0;
    }, _this._handleSpy = function () {
      if (_this.timer) {
        clearTimeout(_this.timer);
      }
      _this.timer = setTimeout(function () {
        return _this.setState({ inViewState: _this._getElemsViewState().viewStatusList });
      }, 20);
    }, _this._initFromProps = function (props) {
      var _ref3 = props || _this.props,
          children = _ref3.children;

      var targetItems = _react.Children.toArray(children).reduce(function (resultArray, child) {
        if ((0, _react.isValidElement)(child)) {
          var _child$props = child.props,
              _child$props$to = _child$props.to,
              to = _child$props$to === undefined ? '' : _child$props$to,
              _child$props$href = _child$props.href,
              href = _child$props$href === undefined ? '' : _child$props$href,
              componentName = child.type.componentName;

          if (componentName === 'Tab') {
            var target = to.replace('#', '') || href.replace('#', '');
            if (resultArray.indexOf(target) === -1) resultArray.push(target);
          }
        }
        return resultArray;
      }, []) || [];
      _this.targetChildren = {};
      _this.setState({
        targetItems: targetItems
      });
      _this._handleSpy();
    }, _temp), _possibleConstructorReturn(_this, _ret);
  } // eslint-disable-line react/sort-comp


  _createClass(TabsContainer, [{
    key: 'componentDidMount',
    // eslint-disable-line react/sort-comp

    value: function componentDidMount() {
      var scrollSpy = this.props.scrollSpy;

      if (scrollSpy) {
        this._initFromProps(this.props);
        window.addEventListener('scroll', this._handleSpy);
      }
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      this._initFromProps(nextProps);
    }
  }, {
    key: 'shouldComponentUpdate',
    value: function shouldComponentUpdate(nextProps, nextState) {
      return !(0, _isEqual3.default)(this.props, nextProps) || !(0, _isEqual3.default)(this.state, nextState);
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      window.removeEventListener('scroll', this._handleSpy);
    }
  }, {
    key: 'renderNav',
    value: function renderNav() {
      var _this2 = this;

      var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          style = _ref4.style;

      var _props = this.props,
          children = _props.children,
          scrollSpy = _props.scrollSpy,
          withHashTag = _props.withHashTag,
          tabDirection = _props.tabDirection,
          props = _objectWithoutProperties(_props, ['children', 'scrollSpy', 'withHashTag', 'tabDirection']);

      var _ref5 = scrollSpy || {},
          _ref5$topOffset = _ref5.topOffset,
          topOffset = _ref5$topOffset === undefined ? 0 : _ref5$topOffset;

      var _state = this.state,
          selectedIndex = _state.selectedIndex,
          inViewState = _state.inViewState;

      delete props.topOffset;
      var i = 0;
      return _react2.default.createElement(
        'nav',
        {
          style: _extends({}, style, { zIndex: 10 }),
          className: (0, _getClassName3.default)('' + tabDirection, _styleModuleImportMap)
        },
        _react.Children.map(children, function (child) {
          if (!(0, _react.isValidElement)(child)) {
            return child;
          }
          var componentName = child.type.componentName;

          var myChild = void 0;
          if (componentName === 'Tab') {
            if (scrollSpy) {
              myChild = _react2.default.cloneElement(child, {
                active: inViewState[i],
                offset: topOffset,
                index: i,
                scrollSpy: scrollSpy,
                withHashTag: withHashTag,
                duration: 300,
                tabDirection: tabDirection
              });
            } else {
              myChild = _react2.default.cloneElement(child, {
                onChange: _this2.onTabsChange,
                active: i === selectedIndex,
                index: i,
                tabDirection: tabDirection
              });
            }
            i += 1;
            return myChild;
          }
          return child;
        })
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var _this3 = this;

      var _props2 = this.props,
          sticky = _props2.sticky,
          tabDirection = _props2.tabDirection,
          props = _objectWithoutProperties(_props2, ['sticky', 'tabDirection']);

      var TabsContainerComponent = void 0;
      switch (tabDirection) {
        case 'column':
          TabsContainerComponent = Column;
          break;
        case 'row':
        default:
          TabsContainerComponent = 'div';
      }

      return _react2.default.createElement(
        TabsContainerComponent,
        (0, _omit2.default)(props, Object.keys(propTypes)),
        sticky ? _react2.default.createElement(
          _reactSticky.Sticky,
          sticky,
          function (_ref6) {
            var distanceFromBottom = _ref6.distanceFromBottom,
                _ref6$style = _ref6.style,
                _ref6$style$top = _ref6$style.top,
                top = _ref6$style$top === undefined ? 0 : _ref6$style$top,
                style = _objectWithoutProperties(_ref6$style, ['top']);

            var topOffset = -1 * sticky.topOffset;
            var styleTopOffset = Math.max(0, topOffset > distanceFromBottom ? topOffset - (topOffset - distanceFromBottom) : topOffset);
            style.top = top + styleTopOffset; // eslint-disable-line no-param-reassign
            return _this3.renderNav({ style: style });
          }
        ) : this.renderNav()
      );
    }
  }]);

  return TabsContainer;
}(_react.PureComponent);

TabsContainer.propTypes = propTypes;
TabsContainer.defaultProps = defaultProps;
TabsContainer.componentName = 'TabsContainer';

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