import { map, mapValues, merge } from 'lodash';

export function buildSelectors(
    localSelectors,
    splatSelector = {},
    subduxes = {}
) {
    const subSelectors = map(subduxes, ({ selectors }, slice) => {
        if (!selectors) return {};
        if (slice === '*') return {};

        return mapValues(
            selectors,
            (func: Function) => (state) => func(state[slice])
        );
    });

    let splat = {};

    for (const name in splatSelector) {
        splat[name] =
            (state) =>
            (...args) => {
                const value = splatSelector[name](state)(...args);

                const res = () => value;
                return merge(
                    res,
                    mapValues(
                        subduxes['*'].selectors,
                        (selector) => () => selector(value)
                    )
                );
            };
    }

    return merge({}, ...subSelectors, localSelectors, splat);
}
