import { Promise } from 'rsvp';
import { ActionTypes } from 'constants/Common';
import departmentApi from 'api/department';
import dispatcher from 'dispatcher';

const COUNTER_SYNC_TIMEOUT = 2000;

function refreshDepartments(ids, extension = 'shallow') {
    let chain = Promise.resolve();

    ids.forEach(id => {
        let options;

        if (id && typeof id === 'object') {
            options = id;
        } else {
            options = { id, extension };
        }

        if (!options.id) {
            return;
        }

        chain = chain.then(() => departmentApi.read(options).then(response => {
            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);
        }));
    });

    return chain;
}

function refreshDepartmentCounters(ids) {
    setTimeout(() => refreshDepartments(ids, 'deep'), COUNTER_SYNC_TIMEOUT);
}

export default {
    refreshDepartments,
    refreshDepartmentCounters,
};
