/*
 * Copyright (C) 2023 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

import {AfterViewInit, Directive, ElementRef, Input} from '@angular/core';
import {IonSearchbar} from '@ionic/angular';

@Directive({
  selector: 'ion-searchbar[autofocus]',
})
export class SearchbarAutofocusDirective implements AfterViewInit {
  @Input() autofocus = true;

  constructor(private element: ElementRef) {}

  ngAfterViewInit() {
    if (!this.autofocus) return;
    const interval = setInterval(() => {
      const searchbar = this.element.nativeElement as IonSearchbar;
      void searchbar.setFocus();
    });
    const onFocus = () => {
      clearInterval(interval);
      this.element.nativeElement.removeEventListener('ionFocus', onFocus);
    };
    this.element.nativeElement.addEventListener('ionFocus', onFocus);
  }
}
