import {
  Directive,
  inject,
  OnInit, output,
  PLATFORM_ID
} from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

@Directive({
  selector: '[webglDetection]',
  standalone: true
})
export class WebglDetectionDirective implements OnInit {
  private readonly platformId = inject(PLATFORM_ID);

  webglSupport = output<boolean>();

  ngOnInit(): void {
    if (!isPlatformBrowser(this.platformId))
      return;

    const supported = this.checkWebGLSupport();
    this.webglSupport.emit(supported);
  }

  private checkWebGLSupport(): boolean {
    let canvas: HTMLCanvasElement | undefined = undefined;
    try {
      canvas = document.createElement('canvas');

      const gl = (
        canvas.getContext('webgl') ||
        canvas.getContext('experimental-webgl')
      ) as WebGLRenderingContext | null;

      const supported =
        !!window.WebGLRenderingContext &&
        !!(gl);

      return supported;
    } catch {
      return false;
    }
    finally {
      canvas?.remove();
    }
  }
}
