import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Store } from '@ngxs/store';
import { Subject } from 'rxjs';
import { take, filter, takeUntil } from 'rxjs/operators';
import { SsoService } from 'sso';
import { AppService } from './core/services/app.service';
import { ModuleSwitcher } from './core/models/app-switcher.enum';
import { AppState } from './core/store/state/app.state';
import { AppConfiguration } from './app-configuration';
import { NativeContainerService } from 'shared/lib/barcode-scanner';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit, OnDestroy {
  title = 'Hugendubel InstoreApp';
  loading = true;
  includeGoogleAnalytics = this.config.includeGoogleAnalytics;
  destroy$ = new Subject();

  get authenticated() {
    return this.ssoService.isAuthenticated();
  }

  constructor(
    private config: AppConfiguration,
    private ssoService: SsoService,
    private appService: AppService,
    private router: Router,
    private store: Store,
    private nativeContainer: NativeContainerService
  ) {
    // intialisations done only when app loads
    this.appService.appLoadInitialisations();
    this.router.events.pipe(filter((e): e is NavigationEnd => e instanceof NavigationEnd)).subscribe(() => {
      if (!this.router.url.includes('login')) {
        // send router navigation events
        this.appService.registerNavigationEvents();
      }
    });
    this.store
      .select(AppState.activeModule)
      .pipe(takeUntil(this.destroy$))
      .subscribe((v: ModuleSwitcher) => {
        v ? document.body.classList.add('branch') : document.body.classList.remove('branch');
      });
  }

  ngOnInit() {
    this.appService.loader$.pipe(take(1)).subscribe(() => {
      this.loading = false;
      this.containerNotificationMessage();
    });
  }

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

  private containerNotificationMessage() {
    // Notify the container app if the user has initialized app loggeed in or not
    // For the purpposes of removing the container Header element
    if (this.nativeContainer.isUiWebview()) {
      this.nativeContainer.sendMessage({ userAuthenticated: this.ssoService.isAuthenticated() });
    }
  }
}
