import isEmpty from './utils';
import ArrayConvertToObj from './array-convert-to-obj';
import { cloneElement, ReactElement } from 'react';

export default function RippleEffectBuild(
    nextRipples: ReactElement[],
    callback: (child: ReactElement) => void,
    prevRipples?: object | null,
) {
    const empty: boolean = isEmpty(prevRipples);
    const preparedRipples: object = empty ? {} : prevRipples;

    switch (empty) {
        case true:
            ArrayConvertToObj(preparedRipples, nextRipples, callback);
            break;

        case false:
            // eslint-disable-next-line no-case-declarations
            const next: object = {};
            ArrayConvertToObj(next, nextRipples, callback);
            for (const rippleKey of Object.keys(next)) {
                if (preparedRipples[rippleKey] == undefined) {
                    preparedRipples[rippleKey] = cloneElement(next[rippleKey], {
                        ...next[rippleKey].props,
                        endLifetime: callback.bind(null, next[rippleKey]),
                    });
                }
            }
            break;
    }

    return preparedRipples;
}
