import { Directive, ElementRef, Output, EventEmitter, HostListener, OnInit, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { skip, takeUntil } from 'rxjs/operators';

@Directive({ selector: '[headerClicked]' })
export class HeaderClickedDirective implements OnInit, OnDestroy {
  headerClicked$ = new Subject();
  destroy$ = new Subject();
  header = document.body.querySelector('.app-header');

  @Output() headerClicked = new EventEmitter<void>();

  @HostListener('document:click', ['$event.target'])
  @HostListener('document:touchstart', ['$event.target'])
  onClick(target: HTMLElement) {
    const isHeaderClicked = this.header.contains(target);

    if (isHeaderClicked) {
      this.headerClicked$.next();
    }
  }

  constructor(private elementRef: ElementRef) {}

  ngOnInit() {
    this.headerClicked$.pipe(takeUntil(this.destroy$)).subscribe((_) => this.headerClicked.emit());
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
