"use strict";

var _react = _interopRequireDefault(require("react"));

require("whatwg-fetch");

var _lodash = _interopRequireDefault(require("lodash"));

var _react2 = require("@storybook/react");

var _addonInfo = require("@storybook/addon-info");

var _addonActions = require("@storybook/addon-actions");

var _index = _interopRequireDefault(require("./index"));

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

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

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

var Search =
/*#__PURE__*/
function (_React$Component) {
  _inherits(Search, _React$Component);

  function Search() {
    var _getPrototypeOf2;

    var _this;

    _classCallCheck(this, Search);

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

    _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Search)).call.apply(_getPrototypeOf2, [this].concat(args)));

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "state", {
      loading: false,
      items: [],
      selectedItem: null,
      data: []
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_fetchRepo", _lodash.default.debounce(
    /*#__PURE__*/
    function () {
      var _ref = _asyncToGenerator(
      /*#__PURE__*/
      regeneratorRuntime.mark(function _callee(val) {
        var res, json;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _this.setState({
                  loading: true
                });

                _context.prev = 1;
                _context.next = 4;
                return fetch("https://api.github.com/search/repositories?q=".concat(val));

              case 4:
                res = _context.sent;
                _context.next = 7;
                return res.json();

              case 7:
                json = _context.sent;

                _this.setState({
                  items: json.items.map(function (item) {
                    return _objectSpread({
                      label: item.html_url
                    }, item);
                  })
                });

                _this.setState({
                  data: json.items
                });

                _context.next = 15;
                break;

              case 12:
                _context.prev = 12;
                _context.t0 = _context["catch"](1);
                console.error(_context.t0);

              case 15:
                _context.prev = 15;

                _this.setState({
                  loading: false
                });

                return _context.finish(15);

              case 18:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this, [[1, 12, 15, 18]]);
      }));

      return function (_x) {
        return _ref.apply(this, arguments);
      };
    }(), 300));

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_handleItemClick",
    /*#__PURE__*/
    function () {
      var _ref2 = _asyncToGenerator(
      /*#__PURE__*/
      regeneratorRuntime.mark(function _callee2(item) {
        var selectedItem;
        return regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                selectedItem = _lodash.default.find(_this.state.data, {
                  html_url: item.label
                });

                _this.setState({
                  selectedItem: selectedItem
                });

              case 2:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      return function (_x2) {
        return _ref2.apply(this, arguments);
      };
    }());

    return _this;
  }

  _createClass(Search, [{
    key: "render",
    value: function render() {
      return _react.default.createElement("div", null, _react.default.createElement(_index.default, {
        placeholder: 'Search github repositories',
        showClearIcon: false,
        onSearch: this._fetchRepo,
        onInputChange: this._fetchRepo,
        onItemClick: this._handleItemClick,
        searchLoading: this.state.loading,
        items: this.state.items,
        labelKey: this.props.labelKey,
        renderItem: this.props.renderItem
      }), this.state.selectedItem && _react.default.createElement("pre", {
        id: "content"
      }, JSON.stringify(this.state.selectedItem, null, 2)));
    }
  }]);

  return Search;
}(_react.default.Component);

(0, _react2.storiesOf)('SearchInput', module).add('Default', (0, _addonInfo.withInfo)('Default')(function () {
  return _react.default.createElement("div", {
    style: {
      margin: 10
    }
  }, _react.default.createElement("h4", null, "Default"), _react.default.createElement(Search, null), _react.default.createElement("h4", null, "Custom Label key"), _react.default.createElement(Search, {
    labelKey: "full_name"
  }), _react.default.createElement("h4", null, "Custom Render Item"), _react.default.createElement(Search, {
    labelKey: "full_name",
    renderItem: function renderItem(item) {
      return _react.default.createElement("div", {
        style: {
          display: 'flex',
          alignItems: 'center'
        }
      }, _react.default.createElement("img", {
        style: {
          width: 30,
          height: 30,
          borderRadius: '50%',
          marginRight: 10
        },
        src: item.owner.avatar_url
      }), _react.default.createElement("div", null, item.full_name));
    }
  }));
}));