import * as React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators, Dispatch } from 'redux';

import { RootState } from 'mweb/common/reducers/root';
import {
  UITrackingPayload,
  trackingTrackClick,
} from 'mweb/common/actions/tracking';
import {
  ContextTypes,
  contextTypeValidator,
} from 'mweb/common/utils/contextTypeValidator';

type UITrackingFunction = (payload: UITrackingPayload) => void;

export interface TrackingContext {
  trackingTrackClick: UITrackingFunction;
  interactionMedium: string;
}

interface TrackingProviderDispatchProps {
  trackingTrackClick: UITrackingFunction;
}

interface TrackingProviderOwnProps {}

interface TrackingProviderProps
  extends TrackingProviderOwnProps,
    TrackingProviderDispatchProps {}

export class TrackingProvider extends React.Component<
  TrackingProviderProps,
  {}
> {
  static childContextTypes: ContextTypes<TrackingContext> = {
    trackingTrackClick: contextTypeValidator,
    interactionMedium: contextTypeValidator,
  };

  getChildContext = (): TrackingContext => {
    return {
      trackingTrackClick: this.props.trackingTrackClick,
      interactionMedium: '',
    };
  };

  render(): JSX.Element {
    return React.Children.only(this.props.children);
  }
}

function mapDispatchToProps(
  dispatch: Dispatch<RootState>,
): TrackingProviderDispatchProps {
  return bindActionCreators(
    {
      trackingTrackClick,
    },
    dispatch,
  );
}

export default connect(undefined, mapDispatchToProps)(
  TrackingProvider,
) as React.ComponentClass<TrackingProviderOwnProps>;
