import { createSelector } from '@ngrx/store';
import { createEntityAdapter, Dictionary, EntityAdapter, EntityState } from '@ngrx/entity';

import {
    BlockActionType,
    BlockActions,
} from '../actions/block.actions';

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

export interface State extends EntityState<Block> {
}

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

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

export function reducer(state = initialState, action: BlockActions): State {
    switch (action.type) {
        case BlockActionType.UPSERT_BLOCK: {
            return adapter.upsertOne(action.payload.block, state);
        }
        case BlockActionType.REMOVE_BLOCK: {
            return adapter.removeOne(action.payload.id, state);
        }
        default: {
            return state;
        }
    }
}

export const {
    selectIds: getIds,
    selectEntities: getEntities,
    selectAll: getAll,
    selectTotal: getTotal,
} = adapter.getSelectors();

export const getEntityById = (id: string) => {
    return createSelector(
        getEntities,
        (entities: Dictionary<Block>) => {
            return entities[id];
        },
    );
};
