import { call, put, takeEvery, select } from 'typed-redux-saga';
import { getApixAdaptor } from '../../utils';
import { specActions } from './slice';

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

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

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

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

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

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

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