import { Component, OnInit, Input, Output, EventEmitter, ViewChild, HostListener, OnChanges } from '@angular/core';
import { ProvisionsService } from '../services/provisions.service'; 
import { Subscription, timer} from 'rxjs';
import { switchMap } from 'rxjs/operators';

@Component({
  selector: 'app-logs',
  templateUrl: './logs.component.html',
  styleUrls: ['./logs.component.scss']
})
export class LogsComponent implements OnInit, OnChanges{

  @ViewChild("insideElement") insideElement;
  @HostListener('document:click', ['$event.target'])

  public onClick(targetElement) {
    const clickedInside = this.insideElement.nativeElement.contains(targetElement);
    if (!clickedInside) {
      this.onClose.emit(false);
    }
  }


  content: String = null;
  sub: Subscription;

  constructor(private _provisionsService: ProvisionsService) { }
  
  @Input() show;
  @Input() selectedprov;
  @Input() type;
  @Output() onClose = new EventEmitter();

  refresh(): void {
    if (!this.content){
      if ( this.type === "provision" ) {
        this.sub = timer(0, 5000).pipe( switchMap(() => this._provisionsService.getProvisionLogs(this.selectedprov._id) ) ).subscribe(content => { 
          this.content = content;
        });
      } else if ( this.type === "destroy" ) {
        this.sub = timer(0, 5000).pipe( switchMap(() => this._provisionsService.getDestroyLogs(this.selectedprov.destroy._id) ) ).subscribe(content => { 
          this.content = content;
        })
      }
    }
  }
  ngOnInit() {}

  ngOnChanges(changes) {
    this.content = null;
    if ( this.sub ) {
      this.sub.unsubscribe();
      this.sub = null;
    }
    if ( changes.show && changes.show.currentValue ) {
      if ( this.type === "provision" ) {
        this.sub = timer(0, 5000).pipe( switchMap(() => this._provisionsService.getProvisionLogs(this.selectedprov._id) ) ).subscribe(content => { 
          this.content = content;
        });
      } else if ( this.type === "destroy" ) {
        this.sub = timer(0, 5000).pipe( switchMap(() => this._provisionsService.getDestroyLogs(this.selectedprov.destroy._id) ) ).subscribe(content => { 
          this.content = content;
        })
      }
    }
  }

  ngOnDestroy() {
    if ( this.sub ) {
      this.sub.unsubscribe();
      this.sub = null;
    }
  }

  close(): void {
    this.content = null;
    if ( this.sub ) {
      this.sub.unsubscribe();
      this.sub = null;
    }
    this.onClose.emit(false);
  }

}
