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

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return 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; }

import React from 'react';
import PropTypes from 'prop-types';
import isFunction from 'is-function';
import isPlainObject from 'is-plain-object';
import channel from './channel';
import createBroadcast from 'brcast';

/**
 * Provide a theme to an entire react component tree via context
 * and event listeners (have to do both context
 * and event emitter as pure components block context updates)
 */

export default function createThemeProvider() {
  var _class, _temp2;

  var CHANNEL = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : channel;

  return _temp2 = _class = function (_React$Component) {
    _inherits(ThemeProvider, _React$Component);

    function ThemeProvider() {
      var _ref;

      var _temp, _this, _ret;

      _classCallCheck(this, ThemeProvider);

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

      return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = ThemeProvider.__proto__ || Object.getPrototypeOf(ThemeProvider)).call.apply(_ref, [this].concat(args))), _this), _this.broadcast = createBroadcast(_this.getTheme()), _this.setOuterTheme = function (theme) {
        _this.outerTheme = theme;
      }, _temp), _possibleConstructorReturn(_this, _ret);
    }

    _createClass(ThemeProvider, [{
      key: 'getTheme',


      // Get the theme from the props, supporting both (outerTheme) => {} as well as object notation
      value: function getTheme(passedTheme) {
        var theme = passedTheme || this.props.theme;
        if (isFunction(theme)) {
          var mergedTheme = theme(this.outerTheme);
          if (!isPlainObject(mergedTheme)) {
            throw new Error('[ThemeProvider] Please return an object from your theme function, i.e. theme={() => ({})}!');
          }
          return mergedTheme;
        }
        if (!isPlainObject(theme)) {
          throw new Error('[ThemeProvider] Please make your theme prop a plain object');
        }

        if (!this.outerTheme) {
          return theme;
        }

        return _extends({}, this.outerTheme, theme);
      }
    }, {
      key: 'getChildContext',
      value: function getChildContext() {
        return _defineProperty({}, CHANNEL, this.broadcast);
      }
    }, {
      key: 'componentDidMount',
      value: function componentDidMount() {
        // create a new subscription for keeping track of outer theme, if present
        if (this.context[CHANNEL]) {
          this.subscriptionId = this.context[CHANNEL].subscribe(this.setOuterTheme);
        }
      }

      // set broadcast state by merging outer theme with own

    }, {
      key: 'componentWillMount',
      value: function componentWillMount() {
        if (this.context[CHANNEL]) {
          this.setOuterTheme(this.context[CHANNEL].getState());
          this.broadcast.setState(this.getTheme());
        }
      }
    }, {
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps) {
        if (this.props.theme !== nextProps.theme) {
          this.broadcast.setState(this.getTheme(nextProps.theme));
        }
      }
    }, {
      key: 'componentWillUnmount',
      value: function componentWillUnmount() {
        if (this.subscriptionId !== undefined) {
          this.context[CHANNEL].unsubscribe(this.subscriptionId);
          delete this.subscriptionId;
        }
      }
    }, {
      key: 'render',
      value: function render() {
        if (!this.props.children) {
          return null;
        }
        return React.Children.only(this.props.children);
      }
    }]);

    return ThemeProvider;
  }(React.Component), _class.propTypes = {
    children: PropTypes.element,
    theme: PropTypes.oneOfType([PropTypes.shape({}), PropTypes.func]).isRequired
  }, _class.childContextTypes = _defineProperty({}, CHANNEL, PropTypes.object.isRequired), _class.contextTypes = _defineProperty({}, CHANNEL, PropTypes.object), _temp2;
}