import { ConnectionService } from 'ng-connection-service';
import { Component, OnInit, Input, Output, EventEmitter, ChangeDetectionStrategy, ViewEncapsulation } from '@angular/core';
import { Observable, BehaviorSubject, combineLatest, merge } from 'rxjs';
import { startWith, map, tap, withLatestFrom, mergeMap } from 'rxjs/operators';
import { trigger, state, style, transition, animate } from '@angular/animations';

@Component({
  selector: 'lib-offline-overlay',
  templateUrl: './offline-overlay.component.html',
  styleUrls: ['./offline-overlay.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  animations: [
    trigger('offline', [
      state('true', style({ transform: 'translateY(0%)' })),
      state('false', style({ transform: 'translateY(-100%)' })),
      transition('true => false', [animate('100ms ease-in')]),
      transition('* => true', [animate('100ms ease-in')]),
    ]),
  ],
})
export class OfflineOverlayComponent implements OnInit {
  offline$: Observable<boolean>;
  closed$ = new BehaviorSubject(false);

  constructor(private connectionService: ConnectionService) {}
  ngOnInit() {
    this.offline$ = this.connectionService.monitor().pipe(
      startWith(true), // By default, we have the connection
      map((v) => !v),
      tap((off) => {
        if (off) {
          this.closed$.next(false);
        }
      })
    );
  }
}
