import { Directive, HostListener, ElementRef, inject } from '@angular/core';
import { Router } from '@angular/router';

/*
 * use this directive to navigate to external links instead of using window.location
 * this is so that guards get activated rather than bypassed
 * sample usage: <a [href]="'https://www.google.com/'" appExternalUrl>Click Me</a>
*/

@Directive({
  selector: 'a[appExternalUrl]'
})
export class ExternalUrlDirective {
  private el = inject(ElementRef);
  private router = inject(Router);


  @HostListener('click', ['$event'])
  clicked(event: Event) {
    const url = this.el.nativeElement.href;
    if (!url) {
      return;
    }

    this.router.navigate(['/externalRedirect', { externalUrl: url }], {
      skipLocationChange: true,
    });

    event.preventDefault();
  }
}
