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

import { Component, Input, NgZone, OnDestroy, OnInit } from '@angular/core';
import { Observable, Subject, timer } from 'rxjs';
import { share, skipWhile, takeUntil } from 'rxjs/operators';
import { SidebarNavItem } from '../bci-sidebar/sidebar-nav-item.model';

@Component({
  selector: 'bci-sidebar-footer',
  templateUrl: './bci-sidebar-footer.component.html',
  styleUrls: ['./bci-sidebar-footer.component.scss'],
})
export class BciSidebarFooterComponent implements OnInit, OnDestroy {
  @Input() public sidebarFooterLinks: SidebarNavItem[];

  @Input() public showTime = false;

  _timeNowSubject = new Subject<number>();
  timeNow: Observable<number> = this._timeNowSubject.pipe(share());

  private componentDestroyed$ = new Subject<void>();

  constructor(private ngZone: NgZone) {}

  ngOnInit() {
    // need to schedule the timer outside of ngZone to avoid infinite waiting in e2e tests, see https://github.com/angular/protractor/issues/3349
    this.ngZone.runOutsideAngular(() => {
      timer(0, 10000)
        .pipe(
          skipWhile(() => !this.showTime),
          takeUntil(this.componentDestroyed$)
        )
        .subscribe(() =>
          this.ngZone.run(() => {
            this._timeNowSubject.next(Date.now());
          })
        );
    });
  }

  ngOnDestroy(): void {
    this.componentDestroyed$.next();
    this.componentDestroyed$.complete();
  }
}
