import { delay } from 'redux-saga';
import { call, cancel, fork, put, takeEvery } from 'redux-saga/effects';
import { CRUD_GET_ONE_REFERENCE, CRUD_DEBOUNCED_GET_MANY } from '../../actions/referenceActions';
import { crudGetMany } from '../../actions/dataActions';

/**
 * Example
 *
 * let id = {
 *   posts: { 4: true, 7: true, 345: true },
 *   authors: { 23: true, 47: true, 78: true },
 * }
 */
const ids = {};
const tasks = {};

// see http://yelouafi.github.io/redux-saga/docs/recipes/index.html#debouncing
function* fetchReference(resource) {
    // combined with cancel(), this debounces the calls
    yield call(delay, 50);
    yield put(crudGetMany(resource, Object.keys(ids[resource])));
    delete ids[resource];
    delete tasks[resource];
}

function* accumulate({ payload }) {
    const { id, resource } = payload;
    if (!ids[resource]) {
        ids[resource] = {};
    }
    ids[resource][id] = true; // fast UNIQUE
    if (tasks[resource]) {
        yield cancel(tasks[resource]);
    }
    tasks[resource] = yield fork(fetchReference, resource);
}

function* accumulateMany({ payload }) {
    console.log(payload);
    const { ids: idArray, resource } = payload;
    if (!ids[resource]) {
        ids[resource] = {};
    }
    idArray.map(id => ids[resource][id] = true); // fast UNIQUE
    if (tasks[resource]) {
        yield cancel(tasks[resource]);
    }
    tasks[resource] = yield fork(fetchReference, resource);
}

export default function* () {
    yield takeEvery(CRUD_GET_ONE_REFERENCE, accumulate);
    yield takeEvery(CRUD_DEBOUNCED_GET_MANY, accumulateMany);
}

@@ -789,352 +789,8 @@
 ) %7B%0A
-    const %7B id, resource %7D = payload;%0A    if (!ids%5Bresource%5D) %7B%0A        ids%5Bresource%5D = %7B%7D;%0A    %7D%0A    ids%5Bresource%5D%5Bid%5D = true; // fast UNIQUE%0A    if (tasks%5Bresource%5D) %7B%0A        yield cancel(tasks%5Bresource%5D);%0A    %7D%0A    tasks%5Bresource%5D = yield fork(fetchReference, resource);%0A%7D%0A%0Afunction* accumulateMany(%7B payload %7D) %7B%0A    console.log(payload);%0A
     
@@ -833,16 +833,16 @@
 ayload;%0A
+
     if (
@@ -1165,27 +1165,103 @@
 FERENCE,
- accumulate
+%0A        (%7B payload %7D) =%3E accumulate(%7B ids: %5Bpayload.id%5D, resource: payload.resource %7D)
 );%0A    y
@@ -1310,17 +1310,13 @@
 cumulate
-Many
 );%0A%7D%0A

use a single `accumulate()`