import { put, takeEvery, takeLatest } from "redux-saga/effects";

import * as indexesAPI from "./api";
import { get as getReference } from "../references/api";
import { apiCall, setPending } from "../sagaUtils";
import {
    WS_UPDATE_INDEX,
    FIND_INDEXES,
    GET_INDEX,
    GET_UNBUILT,
    CREATE_INDEX,
    GET_INDEX_HISTORY,
    GET_REFERENCE, LIST_READY_INDEXES
} from "../actionTypes";

export function* watchIndexes () {
    yield takeLatest(WS_UPDATE_INDEX, wsUpdateIndex);
    yield takeLatest(FIND_INDEXES.REQUESTED, findIndexes);
    yield takeLatest(GET_INDEX.REQUESTED, getIndex);
    yield takeLatest(GET_UNBUILT.REQUESTED, getUnbuilt);
    yield takeEvery(CREATE_INDEX.REQUESTED, createIndex);
    yield takeLatest(GET_INDEX_HISTORY.REQUESTED, getIndexHistory);
    yield takeLatest(LIST_READY_INDEXES.REQUESTED, listReadyIndexes);
}

export function* wsUpdateIndex (action) {
    yield findIndexes({ refId: action.data.reference.id, page: 1 });
    yield apiCall(getReference, { referenceId: action.data.reference.id }, GET_REFERENCE);
}

export function* findIndexes (action) {
    yield apiCall(indexesAPI.find, action, FIND_INDEXES);
}

export function* getIndex (action) {
    yield apiCall(indexesAPI.get, action, GET_INDEX);
}

export function* getUnbuilt (action) {
    yield apiCall(indexesAPI.getUnbuilt, action, GET_UNBUILT);
}

export function* listReadyIndexes (action) {
    yield apiCall(indexesAPI.listReady, action, LIST_READY_INDEXES);
}

export function* createIndex (action) {
    yield setPending(apiCall(indexesAPI.create, action, CREATE_INDEX));
    yield put({
        type: FIND_INDEXES.REQUESTED,
        refId: action.refId,
        page: 1
    });
}

export function* getIndexHistory (action) {
    yield setPending(apiCall(indexesAPI.getHistory, action, GET_INDEX_HISTORY));
}

@@ -28,16 +28,24 @@
 keLatest
+, select
  %7D from 
@@ -66,17 +66,16 @@
 fects%22;%0A
-%0A
 import *
@@ -107,65 +107,8 @@
 i%22;%0A
-import %7B get as getReference %7D from %22../references/api%22;%0A
 impo
@@ -294,16 +294,20 @@
 FERENCE,
+%0A   
  LIST_RE
@@ -851,34 +851,91 @@
     
-yield findIndexes(%7B 
+const refId = yield select(state =%3E state.references.detail.id);%0A%0A    if (
 refId
-:
+ ===
  act
@@ -959,65 +959,43 @@
 e.id
-, page: 1 %7D);%0A    yield apiCall(getReference, %7B reference
+) %7B%0A        yield findIndexes(%7B ref
 Id: 
@@ -1022,27 +1022,27 @@
 e.id
- %7D, GET_REFERENCE);
+, page: 1 %7D);%0A    %7D
 %0A%7D%0A%0A

Fix reference index list creation bug