import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { UnsubscribeDirective } from '@msfa-directives/unsubscribe.directive';
import { filter } from 'rxjs/operators';

@Component({
  selector: 'msfa-skip-to-content',
  templateUrl: './skip-to-content.component.html',
  styleUrls: ['./skip-to-content.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SkipToContentComponent extends UnsubscribeDirective {
  @Input() mainContentId: string;
  skipLinkPath: string;

  constructor(private router: Router, private changeDetectorRef: ChangeDetectorRef) {
    super();
    super.unsubscribeOnDestroy(
      this.router.events.pipe(filter((event: NavigationEnd) => event instanceof NavigationEnd)).subscribe(({ url }) => {
        const mainContentId = `#${this.mainContentId}`;
        // Check if the current URL already includes the mainContentId.
        const existsInUrl: boolean = url.substring(url.length - mainContentId.length, url.length) === mainContentId;

        this.skipLinkPath = existsInUrl ? url : `${url}${mainContentId}`;
        this.changeDetectorRef.markForCheck();
      })
    );
  }
}
