import * as React from 'react';
import { BranchEvent, trackBranchEvent } from './branchUtils';

export interface BranchTimedTrackerProps {
  sessionID: string;
  deviceID: string;
  delaySecondsUntilTrack: number;
  event: BranchEvent;
}

export class BranchTimedTracker extends React.Component<
  BranchTimedTrackerProps
> {
  private trackingTimerHandle: number | undefined;

  public componentDidMount(): void {
    this.trackingTimerHandle = window.setTimeout(
      this.trackEvent,
      this.props.delaySecondsUntilTrack * 1000,
    );
  }

  public componentWillUnmount(): void {
    if (this.trackingTimerHandle) {
      window.clearTimeout(this.trackingTimerHandle);
    }
  }

  public render(): null {
    return null;
  }

  public trackEvent = () => {
    trackBranchEvent(this.props.event, {
      device_id: this.props.deviceID,
      session_id: this.props.sessionID,
    });
  };
}
