// @flow

import * as React from 'react';
import classnames from 'classnames';
import type {HigherOrderComponent} from 'react-flow-types';

type Theme = { [className: string]: string };
export type MergeThemeHOC<T: Theme> = T => HigherOrderComponent<{theme?: $Shape<T>}, {theme: T}>;

const mergeTheme: MergeThemeHOC<*> = (injectedTheme: Theme) => (Component: any): any => {
    return (props) => {
        let theme: Theme = injectedTheme;
        if (props && props.theme) {
            const passedTheme: $Shape<Theme> = props.theme;
            theme = Object.keys(passedTheme)
                .filter((key: string) => !!injectedTheme[key])
                .reduce((accum: Theme, key: string) => {
                    accum[key] = classnames(passedTheme[key], injectedTheme[key]);
                    return accum;
                }, { ...passedTheme, ...injectedTheme });
        }
        return <Component {...props} theme={theme} />;
    };
};