import React from 'react';
import { EventTypes } from 'App/Constant';
import { Services } from '../../../ServiceLocator';

const AnalyticsWrapper = ({ targetId, data, children }) => {
    const { props } = children;
    const events = {};
    if (props.onClick) {
        events.onClick = (...args) => {
            props.onClick(...args);
            Services.analytics.triggerEvent(EventTypes[targetId], data);
        };
    }
    if (props.onChange) {
        events.onChange = (...args) => {
            props.onChange(...args);
            Services.analytics.triggerEvent(EventTypes[targetId], args[1]);
        };
    }
    return React.cloneElement(children, { ...props, ...events });
};

export const withAnalyticsTarget = (fn, targetId, data) => (...args) => {
    Services.analytics.triggerEvent(EventTypes[targetId], data);
    return fn(...args);
};

export default AnalyticsWrapper;
