import * as React from 'react';
import * as ReactGA from 'react-ga';

const doNotTrack = (
  // Do not add Google Analytics when building the static site...
  typeof window === 'undefined'
  // ...or when DoNotTrack is enabled:
  || (
    typeof window.navigator !== 'undefined'
    && window.navigator.doNotTrack === '1'
  )
);

export const initialize = wrapFunction(ReactGA.initialize);
export const set = wrapFunction(ReactGA.set);
export const pageview = wrapFunction(ReactGA.pageview);
export const modalview = wrapFunction(ReactGA.modalview);
export const event = wrapFunction(ReactGA.event);
export const timing = wrapFunction(ReactGA.timing);
export const ga = wrapFunction(ReactGA.ga);
export const outboundLink = wrapFunction(ReactGA.outboundLink);
export const exception = wrapFunction(ReactGA.exception);

export class OutboundLink extends ReactGA.OutboundLink {
  public render() {
    if (doNotTrack) {
      // Make sure <OutboundLink>'s custom props do not get passed on to the <a>:
      const aProps = { ...this.props };
      delete aProps.to;
      delete aProps.eventLabel;
      delete aProps.trackerNames;

      return (
        <a
          href={this.props.to}
          {...aProps}
        />
      );
    }

    return (
      <ReactGA.OutboundLink
        {...this.props as any}
      />
    );
  }
}

function wrapFunction<T extends Function>(functionToWrap: T): T {
  if (doNotTrack) {
    return (() => undefined) as any;
  }

  return functionToWrap;
}
