/*
 * Copyright (C) 2019 Robert Bosch GmbH Copyright (C) 2019 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import {
  Directive,
  ElementRef,
  EventEmitter,
  HostListener,
  Input,
  OnChanges,
  Output,
  SimpleChanges
} from '@angular/core';

@Directive({
  selector: '[bciFullscreen]'
})
export class FullscreenDirective implements OnChanges {
  @Input() bciFullscreen: boolean;
  @Output() readonly bciFullscreenChange = new EventEmitter<boolean>();

  @HostListener('fullscreenchange', ['$event'])
  @HostListener('webkitfullscreenchange', ['$event'])
  @HostListener('mozfullscreenchange', ['$event'])
  @HostListener('MSFullscreenChange', ['$event'])
  onFullscreenChanged(): void {
    this.bciFullscreen = !!(document.fullscreenElement || document['mozFullScreenElement'] || document['webkitFullscreenElement'] || document['msFullscreenElement']);

    this.bciFullscreenChange.emit(this.bciFullscreen);
  }

  constructor(private element: ElementRef) {
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (!(document.fullscreenEnabled ||
      document['mozFullScreenEnabled'] ||
      document.documentElement['webkitRequestFullScreen'])) {
      return;
    }

    if (this.bciFullscreen) {
      return this.activateFullscreen();
    }

    if (!!changes.bciFullscreen.previousValue && !changes.bciFullscreen.currentValue) {
      this.deactivateFullscreen();
    }
  }

  activateFullscreen(): void {
    this.execute(this.element.nativeElement, [
      'requestFullscreen',
      'webkitRequestFullScreen',
      'mozRequestFullScreen',
      'msRequestFullscreen'
    ]);
  }

  deactivateFullscreen() {
    try {
      this.execute(document, ['exitFullscreen', 'mozCancelFullScreen', 'webkitExitFullscreen', 'msExitFullscreen']);
      // eslint-disable-next-line no-empty
    } catch (e) {
    }
  }

  private execute(element: Document | ElementRef, methods: Array<string>) {
    const call = methods.filter((method) => !!element[method])[0];
    if (call) {
      return element[call]();
    }
  }
}
