import { Injectable, Inject } from '@angular/core';
import {
  animate,
  AnimationBuilder,
  AnimationPlayer,
  style
} from '@angular/animations';
import { DOCUMENT } from '@angular/common';
import { Router, NavigationEnd } from '@angular/router';
import { filter, take } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class SplashScreenService {
  splashScreenEl: any;
  player: AnimationPlayer;

  public constructor(
    private animationBuilder: AnimationBuilder,
    @Inject(DOCUMENT) private document: Document,
    private router: Router
  ) {
    this.init();
  }

  private init(): void {
    // Get the splash screen element
    this.splashScreenEl = this.document.body.querySelector('#splash-screen');

    // If the splash screen element exists...
    if (this.splashScreenEl) {
      // Hide it on the first NavigationEnd event
      this.router.events
        .pipe(
          filter(event => event instanceof NavigationEnd),
          take(1)
        )
        .subscribe(() => {
          setTimeout(() => {
            this.hide();
          });
        });
    }
  }

  /**
   * Show the splash screen
   */
  show(): void {
    this.player = this.animationBuilder
      .build([
        style({
          opacity: '0',
          zIndex: '99999'
        }),
        animate('400ms ease', style({ opacity: '1' }))
      ])
      .create(this.splashScreenEl);

    setTimeout(() => {
      this.player.play();
    }, 0);
  }

  /**
   * Hide the splash screen
   */
  hide(): void {
    this.player = this.animationBuilder
      .build([
        style({ opacity: '1' }),
        animate(
          '700ms ease',
          style({
            opacity: '0',
            display: 'none',
            zIndex: '-10'
          })
        )
      ])
      .create(this.splashScreenEl);

    setTimeout(() => {
      this.player.play();
    }, 0);
  }
}
