"use strict";

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

var _typedReduxSaga = require("typed-redux-saga");

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

var _slice = require("./slice");

function* initSaga(action) {
  var {
    initSpecsSuccessAction,
    initSpecsFailureAction
  } = _slice.specActions;
  var adaptor = (0, _utils.getApixAdaptor)();

  try {
    var specs = yield* (0, _typedReduxSaga.call)([adaptor, 'fetchSpecList']);
    var currentSpecKey = action.payload.specKey;

    if (!currentSpecKey) {
      currentSpecKey = Object.values(specs).find(spec => spec.status === 'current').key;
    }

    var spec = yield* (0, _typedReduxSaga.call)([adaptor, 'fetchSpec'], specs[currentSpecKey]);
    specs[currentSpecKey] = spec;
    yield* (0, _typedReduxSaga.put)(initSpecsSuccessAction({
      specs,
      currentSpecKey
    }));
  } catch (error) {
    yield* (0, _typedReduxSaga.put)(initSpecsFailureAction(new Error(error.message)));
  }
}

function* setCurrentSpecSaga(action) {
  var {
    setCurrentSpecSuccessAction,
    setCurrentSpecFailureAction
  } = _slice.specActions;
  var adaptor = (0, _utils.getApixAdaptor)();
  var spec = yield* (0, _typedReduxSaga.select)(state => state.specs.specs[action.payload.currentSpecKey]);

  try {
    var newSpec = yield* (0, _typedReduxSaga.call)([adaptor, 'fetchSpec'], spec);
    yield* (0, _typedReduxSaga.put)(setCurrentSpecSuccessAction({
      api: newSpec.api,
      currentSpecKey: action.payload.currentSpecKey
    }));
  } catch (error) {
    yield (0, _typedReduxSaga.put)(setCurrentSpecFailureAction(new Error(error.message)));
  }
}

function* saga() {
  var {
    initSpecsAction,
    setCurrentSpecAction
  } = _slice.specActions;
  yield* (0, _typedReduxSaga.takeEvery)(initSpecsAction, initSaga);
  yield* (0, _typedReduxSaga.takeEvery)(setCurrentSpecAction, setCurrentSpecSaga);
}
//# sourceMappingURL=sagas.js.map