import { createFeature, createReducer, on, createSelector } from '@ngrx/store';
import { createEntityAdapter, EntityState } from '@ngrx/entity';

import { Block } from '../models';

import { actions } from './block.actions';

const adapter = createEntityAdapter<Block>({
    selectId: block => block.id,
});

interface State {
    blocks: EntityState<Block>;
}

const initialState: State = {
    blocks: adapter.getInitialState(),
};

export const feature = createFeature({
    name: `@module.class.name@_block`,
    reducer: createReducer(
        initialState,
        on(actions.upsertBlock, (state, action) => ({
            ...state,
            blocks: adapter.upsertOne(action.block, state.blocks),
        })),
        on(actions.removeBlock, (state, action) => ({
            ...state,
            blocks: adapter.removeOne(action.id, state.blocks),
        })),
    ),
    extraSelectors: ({
                         selectBlocks,
                     }) => {
        const getBlockEntities = createSelector(
            selectBlocks,
            adapter.getSelectors().selectEntities,
        );
        const getBlock = (id: string) => createSelector(
            getBlockEntities,
            entities => entities[id],
        );
        return {
            getBlock,
        };
    },
});
