import React, { Component, ErrorInfo, ReactNode } from 'react';
import atlasJSON from '../../../mocks/atlas/items/items.json';
import atlasIMG from '../../../mocks/atlas/items/items.png';
import { SpriteFromAtlas } from '../../shared/SpriteFromAtlas';

interface Props {
  children?: ReactNode;
}

interface State {
  hasError: boolean;
}

export class ErrorBoundary extends Component<Props, State> {
  public state: State = {
    hasError: false,
  };

  public static getDerivedStateFromError(_: Error): State {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error('Uncaught error:', error, errorInfo);
  }

  public render() {
    if (this.state.hasError) {
      return (
        <SpriteFromAtlas
          atlasIMG={atlasIMG}
          atlasJSON={atlasJSON}
          spriteKey={'others/no-image.png'}
          imgScale={3}
        />
      );
    }

    return this.props.children;
  }
}
