'use strict';

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

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _channel = require('./channel');

var _channel2 = _interopRequireDefault(_channel);

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

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 createThemeListener() {
  var CHANNEL = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _channel2.default;

  var contextTypes = _defineProperty({}, CHANNEL, _propTypes2.default.object.isRequired);

  function initial(context) {
    if (!context[CHANNEL]) {
      throw new Error('[' + this.displayName + '] Please use ThemeProvider to be able to use WithTheme');
    }

    return context[CHANNEL].getState();
  }

  function subscribe(context, cb) {
    if (context[CHANNEL]) {
      return context[CHANNEL].subscribe(cb);
    }
  }

  function unsubscribe(context, subscriptionId) {
    if (context[CHANNEL]) {
      context[CHANNEL].unsubscribe(subscriptionId);
    }
  }

  return {
    contextTypes: contextTypes,
    initial: initial,
    subscribe: subscribe,
    unsubscribe: unsubscribe
  };
}