'use strict';

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

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _Dock = require('../../../styles/cspace-ui/Dock.css');

var _Dock2 = _interopRequireDefault(_Dock);

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

/* global window */

const propTypes = {
  children: _propTypes2.default.element,
  dockTop: _propTypes2.default.number,
  isSidebarOpen: _propTypes2.default.bool
};

const defaultProps = {
  isSidebarOpen: true
};

class Dock extends _react.Component {
  constructor(props) {
    super(props);
    this.setDomNode = this.setDomNode.bind(this);
    this.handleScroll = this.handleScroll.bind(this);

    this.state = {
      docked: false
    };
  }

  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll, false);
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll, false);
  }

  setDomNode(ref) {
    this.domNode = ref;
  }

  handleScroll() {
    const node = this.domNode;

    if (!node) return;

    const dockTop = this.props.dockTop;


    if (this.state.docked) {
      if (window.scrollY + dockTop < node.offsetTop) {
        this.setState({
          docked: false
        });
      }
    } else if (window.scrollY + dockTop >= node.offsetTop) {
      this.setState({
        docked: true
      });
    }
  }

  render() {
    var _props = this.props;
    const children = _props.children,
          dockTop = _props.dockTop,
          isSidebarOpen = _props.isSidebarOpen;
    const docked = this.state.docked;


    const className = (0, _classnames2.default)(isSidebarOpen ? _Dock2.default.normal : _Dock2.default.full, { [_Dock2.default.docked]: docked });

    const inlineStyle = docked ? { height: this.domNode.offsetHeight } : {};

    const innerInlineStyle = docked ? { top: dockTop || 0 } : {};

    return _react2.default.createElement(
      'header',
      {
        className: className,
        style: inlineStyle,
        ref: this.setDomNode
      },
      _react2.default.createElement(
        'div',
        { style: innerInlineStyle },
        children
      )
    );
  }
}

exports.default = Dock;
Dock.propTypes = propTypes;
Dock.defaultProps = defaultProps;