import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable, of, Subscription } from 'rxjs';
import { catchError, exhaustMap, map, tap, take } from 'rxjs/operators';

import { AuthSelector } from '@overflow/shared/auth/store';
import { DomainMember } from '@overflow/commons-typescript/model/domain';
import { InfraHost } from '@overflow/commons-typescript/model/infra';
import { InfraHostService } from '../service/infra-host.service';

@Component({
  selector: 'of-infra-host',
  templateUrl: './infra-host.component.html',
})
export class InfraHostComponent implements OnInit {

  @Input() infraHost: InfraHost;
  @Input() infraHostID: number;
  error$: Observable<any>;
  pending$: Observable<boolean>;

  constructor(
    private infraHostService: InfraHostService,
  ) {
  }

  ngOnInit() {
    if (undefined === this.infraHost && undefined === this.infraHostID) {
      // Create
    } else if (undefined !== this.infraHost && undefined === this.infraHostID) {
      // use infraHost
    } else if (undefined === this.infraHost && undefined !== this.infraHostID) {
      // get infraHost
      this.infraHostService.read(this.infraHostID)
        .pipe(
          tap(() => {
            this.pending$ = of(true);
          }),
          map((infraHost: InfraHost) => {
            this.infraHost = infraHost;
          }),
          catchError(error => {
            this.error$ = of(error);
            return of();
          }),
          tap(() => {
            this.pending$ = of(false);
          }),
          take(1),
      ).subscribe();
    } else {
      // error
    }
  }

}