import { ChangeDetectorRef, ElementRef } from '@angular/core';

export class UiHelper {

  public static focusAndSelectFirstInput(
    elementRef: ElementRef,
    changeDetectorRef?: ChangeDetectorRef,
    switchedTab = false,
    skipFirstFocusableInput = false,
  ): boolean {
    if (switchedTab) {
      changeDetectorRef?.detectChanges();
    }
    let focusableInputFound = false;
    const inputs = elementRef?.nativeElement?.parentElement?.getElementsByTagName('input') as HTMLCollection;
    if (inputs && inputs.length) {
      let index = 0;
      let input;
      while (index < inputs.length) {
        input = inputs.item(index) as HTMLElement;
        // skip radios or checkboxes or hidden input fields
        const inputClassList = input.classList as DOMTokenList;
        const skipInput = (
          input?.type === 'radio' || input?.type === 'checkbox' || (inputClassList && inputClassList.contains('hide'))
        );
        if (!skipInput) {
          if (skipFirstFocusableInput) {
            skipFirstFocusableInput = false;
          } else {
            input.focus({
              preventScroll: true,
            });
            input.select();
            focusableInputFound = true;
            break;
          }
        }
        index++;
      }
    }
    if (focusableInputFound && !switchedTab) {
      changeDetectorRef?.detectChanges();
    }
    return focusableInputFound;
  }

  public static focusPrimaryButton(elementRef: ElementRef) {
    const primaryButtons = elementRef?.nativeElement?.parentElement?.querySelectorAll('button.mat-primary') as NodeList;
    if (primaryButtons && primaryButtons.length) {
      const primaryButton = primaryButtons[0] as HTMLElement;
      if (primaryButton) {
        primaryButton.focus();
      }
    }
  }

}
