const splitChunks = require('./splitChunks');

class PromisePool {
    constructor(items = [], toPromise = Promise.resolve) {
        this._items = items;
        this._toPromise = toPromise;
    }
    resolveChunked(chunkSize, onChunkResolve) {
        let chain = Promise.resolve([]);
        let chunks = splitChunks(this._items, chunkSize);

        for (let i = 0; i < chunks.length; i++) {
            chain = chain.then(data => {
                return Promise.all(chunks[i].map(this._toPromise))
                    .then(chunkData => {
                        let resolvedData = data.concat(chunkData);

                        if (onChunkResolve) {
                            // сигнатура forEach
                            onChunkResolve(chunkData, i, resolvedData);
                        }

                        return resolvedData;
                    });
            });
        }

        return chain;
    }
    resolveQueue(onItemResolve) {
        return this.resolveChunked(1, onItemResolve && ((chunk, i, data) => onItemResolve(chunk[0], i, data)));
    }
    resolveBulk() {
        return this.resolveChunked(Infinity, null);
    }
}

module.exports = PromisePool;
