import { ErrorInfo, PureComponent } from 'react';
import { Native as Sentry } from 'sentry-expo';
import * as Updates from 'expo-updates';

type TProps = {
  children: React.ReactElement;
};

/*
 * https://github.com/expo/sentry-expo/issues/23#issuecomment-398666767
 * https://docs.sentry.io/platforms/javascript/react/
 * */
// This is a way to handle all errors in the app.

export class ErrorBoundary extends PureComponent<TProps> {
  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    // @ts-ignore
    const { name } = this;
    Sentry.withScope(scope => {
      scope.setExtras((errorInfo as unknown) as Record<string, unknown>);
      if (name) {
        scope.addBreadcrumb({ message: name });
        scope.setTag('errorInComponent', name);
      }
      // const eventId = Sentry.Native.captureException(error);
      Sentry.captureException(error);
    });
    // @ts-ignore
    if (!global.__DEV__) {
      return;
    }
    Updates.reloadAsync();
  }

  render() {
    const { children } = this.props;

    //when there's not an error, render children untouched
    return children;
  }
}
