'use strict';

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

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 _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactIntl = require('react-intl');

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

var _SearchConditionInput = require('./input/SearchConditionInput');

var _SearchConditionInput2 = _interopRequireDefault(_SearchConditionInput);

var _PanelContainer = require('../../containers/layout/PanelContainer');

var _searchOperators = require('../../constants/searchOperators');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: 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; }

var messages = (0, _reactIntl.defineMessages)({
  title: {
    'id': 'advancedSearchBuilder.title',
    'defaultMessage': 'Advanced Search'
  }
});

var propTypes = {
  condition: _propTypes2.default.instanceOf(_immutable2.default.Map),
  config: _propTypes2.default.object,
  inline: _propTypes2.default.bool,
  readOnly: _propTypes2.default.bool,
  recordType: _propTypes2.default.string,
  onConditionCommit: _propTypes2.default.func
};

var childContextTypes = {
  recordType: _propTypes2.default.string
};

var AdvancedSearchBuilder = function (_Component) {
  _inherits(AdvancedSearchBuilder, _Component);

  function AdvancedSearchBuilder() {
    _classCallCheck(this, AdvancedSearchBuilder);

    return _possibleConstructorReturn(this, (AdvancedSearchBuilder.__proto__ || Object.getPrototypeOf(AdvancedSearchBuilder)).apply(this, arguments));
  }

  _createClass(AdvancedSearchBuilder, [{
    key: 'getChildContext',
    value: function getChildContext() {
      var recordType = this.props.recordType;


      return {
        recordType: recordType
      };
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.normalizeCondition();
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate() {
      this.normalizeCondition();
    }
  }, {
    key: 'normalizeCondition',
    value: function normalizeCondition() {
      var _props = this.props,
          condition = _props.condition,
          config = _props.config,
          recordType = _props.recordType,
          onConditionCommit = _props.onConditionCommit;

      // FIXME: Uncomment this once conditions may be added by the end user.

      // if (!condition && onConditionCommit) {
      //   const defaultCondition = get(config, ['recordTypes', recordType, 'advancedSearch']);
      //
      //   if (defaultCondition) {
      //     onConditionCommit(Immutable.fromJS(defaultCondition));
      //   }
      // }

      // FIXME: There will be no need for this once conditions may be added by the end user.
      // For now do a quick and dirty merge of the (possibly normalized) condition into the
      // default, so that fields aren't unrecoverable after normalization.

      if (onConditionCommit) {
        var defaultCondition = _immutable2.default.fromJS((0, _get2.default)(config, ['recordTypes', recordType, 'advancedSearch']));

        if (defaultCondition && condition) {
          if (condition.get('op') !== defaultCondition.get('op') || !_immutable2.default.List.isList(condition.get('value')) || condition.get('value').size !== defaultCondition.get('value').size) {
            var mergedCondition = defaultCondition;
            var clauses = void 0;

            var op = condition.get('op');

            if (op === _searchOperators.OP_AND || op === _searchOperators.OP_OR) {
              mergedCondition = mergedCondition.set('op', op);

              clauses = condition.get('value');
            } else {
              clauses = _immutable2.default.List([condition]);
            }

            clauses.forEach(function (clause) {
              var targetClauses = mergedCondition.get('value');

              var index = targetClauses.findKey(function (targetClause) {
                return targetClause.get('path') === clause.get('path');
              });

              if (typeof index !== 'undefined') {
                var targetClause = targetClauses.get(index);

                var value = clause.get('value');

                if (targetClause.get('op') === _searchOperators.OP_RANGE && !_immutable2.default.List.isList(value)) {
                  value = clause.get('op') === _searchOperators.OP_GTE ? _immutable2.default.List([value]) : _immutable2.default.List([undefined, value]);
                }

                mergedCondition = mergedCondition.setIn(['value', index, 'value'], value);
              }
            });

            if (!mergedCondition.equals(condition)) {
              onConditionCommit(mergedCondition);
            }
          }
        } else {
          onConditionCommit(defaultCondition);
        }
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _props2 = this.props,
          condition = _props2.condition,
          config = _props2.config,
          inline = _props2.inline,
          readOnly = _props2.readOnly,
          recordType = _props2.recordType,
          onConditionCommit = _props2.onConditionCommit;


      if (!condition) {
        return null;
      }

      var fieldDescriptor = (0, _get2.default)(config, ['recordTypes', recordType, 'fields']);

      var searchConditionInput = _react2.default.createElement(_SearchConditionInput2.default, {
        condition: condition,
        fields: fieldDescriptor,
        inline: inline,
        readOnly: readOnly,
        onCommit: onConditionCommit
      });

      if (inline) {
        return searchConditionInput;
      }

      var panelHeader = _react2.default.createElement(
        'h3',
        null,
        _react2.default.createElement(_reactIntl.FormattedMessage, messages.title)
      );

      return _react2.default.createElement(
        _PanelContainer.ConnectedPanel,
        {
          collapsible: true,
          header: panelHeader,
          name: 'advancedSearch',
          recordType: recordType
        },
        searchConditionInput
      );
    }
  }]);

  return AdvancedSearchBuilder;
}(_react.Component);

exports.default = AdvancedSearchBuilder;


AdvancedSearchBuilder.propTypes = propTypes;
AdvancedSearchBuilder.childContextTypes = childContextTypes;