import {Component, OnInit} from '@angular/core';
import {IntervalObservable} from "rxjs/observable/IntervalObservable";
import {BBService} from "./bb.service";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [BBService]
})

export class AppComponent implements OnInit {

  title = 'Bulletin-Board Server';
  status = 'Not connected';
  errorMessage = '';

  private alive: boolean;  // used to unsubscribe from the IntervalObservable
                           // when OnDestroy is called.

  constructor(private bbservice : BBService) { }


  ngOnInit(): void {

    // Get initial status
    this.bbservice.getStatus().subscribe(
      status => { this.status = status.name; this.errorMessage = ""; },
      error => { this.status = "Not connected"; this.errorMessage = <any>error; }
    );

    this.alive = true;
    // Get new status every second
    let o = IntervalObservable.create(1000)
      //.takeWhile(() => this.alive) // only fires when component is alive
      .subscribe(n => {
        if (!this.alive) {
          o.unsubscribe();
          return;
        }
        this.bbservice.getStatus().subscribe(
          status => { this.status = status.name + " " + n; this.errorMessage = ""; },
          error => { this.errorMessage = <any>error; this.status = "Not connected"; }
        );
      });
  }


  ngOnDestroy(){
    this.alive = false; // switches your IntervalObservable off
  }

}


