import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { ErrorLink } from './error-link.model';

@Component({
  selector: 'ui-error-list',
  templateUrl: './error-list.component.html',
  styleUrls: ['./error-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ErrorListComponent {
  @Input() uiErrorLinks: ErrorLink[] = [];
  @Input() uiHeadingText: string;
  @Input() uiDescription: string;

  setFocusOnFormElement(element: HTMLElement): void {
    const id = element.getAttribute('href').replace('#', '');
    const target = document.getElementById(id);

    if (target) {
      const targetPosition: DOMRect = target.getBoundingClientRect();
      const absoluteElementPosition = targetPosition.top + window.scrollY;
      const newPosition = absoluteElementPosition - window.innerHeight / 2;

      if (target.focus) {
        console.log(target);
        target.tabIndex = -1;
        target.focus();
        window.scrollTo(0, newPosition);
        target.tabIndex = 0;
      }
    }
  }
}
