"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 _reactBootstrapTypeahead = require("react-bootstrap-typeahead");

var _selectn = require("selectn");

var _selectn2 = _interopRequireDefault(_selectn);

var _utils = require("./utils");

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 DEFAULT_OPTIONS = {
  required: false,
  labelKey: "name",
  minLength: 3,
  placeholder: "Search..."
};

var defaultSearch = function defaultSearch(url, query) {
  return fetch("url?query=" + query).then(function (res) {
    return res.json();
  });
};

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

  function AsyncTypeaheadField(props) {
    _classCallCheck(this, AsyncTypeaheadField);

    var _this = _possibleConstructorReturn(this, (AsyncTypeaheadField.__proto__ || Object.getPrototypeOf(AsyncTypeaheadField)).call(this, props));

    _this.handleSearch = function (query) {
      if (!query) {
        return;
      }

      var _this$props$uiSchema$ = _this.props.uiSchema.asyncTypeahead,
          url = _this$props$uiSchema$.url,
          optionsPath = _this$props$uiSchema$.optionsPath,
          _this$props$uiSchema$2 = _this$props$uiSchema$.search,
          search = _this$props$uiSchema$2 === undefined ? defaultSearch : _this$props$uiSchema$2;


      search(url, query).then(function (json) {
        return optionsPath ? (0, _selectn2.default)(optionsPath, json) : json;
      }).then(function (options) {
        return _this.setState({ options: options });
      });
    };

    _this.handleSelectionChange = function (events) {
      if (events.length > 0) {
        var _this$props = _this.props,
            schema = _this$props.schema,
            _this$props$uiSchema$3 = _this$props.uiSchema.asyncTypeahead,
            mapping = _this$props$uiSchema$3.mapping,
            _this$props$uiSchema$4 = _this$props$uiSchema$3.cleanAfterSelection,
            cleanAfterSelection = _this$props$uiSchema$4 === undefined ? true : _this$props$uiSchema$4,
            onChange = _this$props.onChange;

        var schemaEvents = (0, _utils.mapSchema)(events, schema, mapping);
        onChange(schemaEvents);
        if (cleanAfterSelection) {
          setTimeout(function () {
            if (_this.refs.typeahead) {
              _this.refs.typeahead.getInstance().clear();
            }
          }, 0);
        }
      }
    };

    _this.state = {
      options: []
    };
    return _this;
  }

  _createClass(AsyncTypeaheadField, [{
    key: "render",
    value: function render() {
      var asyncTypeahead = this.props.uiSchema.asyncTypeahead;


      var typeConf = Object.assign({}, DEFAULT_OPTIONS, asyncTypeahead);
      typeConf.onChange = this.handleSelectionChange;
      typeConf.onSearch = this.handleSearch;
      typeConf.options = this.state.options;
      typeConf.ref = "typeahead";
      typeConf.labelKey = (0, _utils.mapLabelKey)(asyncTypeahead.labelKey);

      return _react2.default.createElement(_reactBootstrapTypeahead.AsyncTypeahead, typeConf);
    }
  }]);

  return AsyncTypeaheadField;
}(_react.Component);

AsyncTypeaheadField.propTypes = {
  schema: _propTypes2.default.object.isRequired,
  uiSchema: _propTypes2.default.shape({
    asyncTypeahead: _propTypes2.default.shape({
      url: _propTypes2.default.string.isRequired,
      optionsPath: _propTypes2.default.string,
      mapping: _propTypes2.default.object,
      cleanAfterSelection: _propTypes2.default.bool,
      search: _propTypes2.default.func
    }).isRequired
  })
};

exports.default = AsyncTypeaheadField;