'use strict';

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

var _lodash = require('lodash');

var _theme = require('../theme');

var createGetter = function createGetter(key) {
  return function (props) {
    var result = (0, _lodash.get)(props, 'theme.' + _theme.NAMESPACE + '.' + key);
    if (!result) {
      throw new Error('Could not find value for theme style getter ' + key + '!');
    }
    return result;
  };
};

/**
 * Creates a getter which will retrieve the specified value from
 * a provided object which contains a `theme`. Use this to create
 * a function to pass to a styled component to select a theme value.
 *
 * Example usage:
 *
 * styled.div`
 *   color: ${themeGet('colors.primary.default')};
 * `;
 */
var themeGet = function themeGet(key) {
  return createGetter(key);
};

var createIf = function createIf(existingConditions) {
  return function (conditionFn, key) {
    var chain = function chain() {
      throw new Error('themeGet.if() chains must be terminated by .else()');
    };

    var conditions = existingConditions.concat({
      test: conditionFn,
      themeKey: key
    });

    chain.if = createIf(conditions);

    chain.else = function (elseKey) {
      return function (props) {
        var matched = conditions.find(function (_ref) {
          var test = _ref.test;
          return test(props);
        });
        if (matched) {
          return createGetter(matched.themeKey)(props);
        } else if (elseKey) {
          // if user provided an else key, try to get it from theme
          try {
            return createGetter(elseKey)(props);
          } catch (err) {
            // if not in theme, treat it as a literal value
            return elseKey;
          }
        } else {
          return '';
        }
      };
    };

    return chain;
  };
};

themeGet.if = createIf([]);

exports.default = themeGet;