import Immutable from 'immutable';
import { ReduceStore } from 'flux/utils';
import { ActionTypes } from 'constants/Common';
import dispatcher from 'dispatcher';
import Chunk from 'records/Chunk';

class ChunkStore extends ReduceStore {
    getInitialState() {
        return new Immutable.Map();
    }

    reduce(state, action) {
        const { data, type } = action;

        switch (type) {
            case ActionTypes.RECEIVE_MIXED_DATA:
                return this._receiveRawData(state, data);
            default:
                return state;
        }
    }

    get(id) {
        return this._state.get(id) || Chunk.create();
    }

    _receiveRawData(state, data) {
        if (!data.chunks) {
            return state;
        }

        const nextState = new Immutable.Map(data.chunks).map((chunkData, key) => {
            const existingChunk = this.get(key);

            if (!existingChunk || chunkData.page <= 1) {
                chunkData.collected_items = chunkData.items;
            } else {
                chunkData.collected_items = existingChunk.getCollectedItems().concat(chunkData.items);
            }

            return Chunk.create(chunkData);
        });

        return state.merge(nextState);
    }
}

export default window.ya.connect.ChunkStore = new ChunkStore(dispatcher);
