import { Component, OnInit, ElementRef, HostListener, AfterViewInit, ViewChild, ChangeDetectorRef, Input, OnDestroy } from '@angular/core';
import { MdbTableDirective, MdbTablePaginationComponent, MDBModalService } from 'angular-bootstrap-md';
import { ProvisionsService } from '../services/provisions.service';
import { AlertService } from '../services/alert.service';
import { ModalInfoComponent } from '../modals/modalinfo.component';
import { ModalConfirmComponent } from '../modals/confirm.component';
import { Subscription, timer } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { ScenariosService } from '../services/scenarios.service';
@Component({
  selector: 'table-provisions',
  templateUrl: './table-provisions.component.html',
  styleUrls: ['./table-provisions.component.scss']
})
export class TableProvisionsAdminComponent implements OnInit, OnDestroy, AfterViewInit {
  
  scenarios;
  subscription: Subscription;
  filter = {
    showDestroyed : false
  };
  filterParams : any = {
    isDestroyed: false
  };
  loading: boolean = false;

  pagingIsDisabled: Boolean = false;

  @ViewChild(MdbTablePaginationComponent, { static: true }) mdbTablePagination: MdbTablePaginationComponent;
  @ViewChild(MdbTableDirective, { static: true }) mdbTable: MdbTableDirective;

  //@ViewChild('row', { static: true }) row: ElementRef;

  elements = [];
  searchText: string = '';
  previous: string;

  @HostListener('input') oninput() {
    this.mdbTablePagination.searchText = this.searchText;
  }

  
  selectedprov: any = null;
  showInfo: boolean = false;
  logShow: boolean = false;
  logstype: String = 'provision';

  maxVisibleItems: number = 25;


  constructor(private modalService: MDBModalService, private _scenariosService: ScenariosService, private _alertService: AlertService, private cdRef: ChangeDetectorRef, private _provisionsService: ProvisionsService) {

  }

  _initElements(): void {
    this.mdbTable.setDataSource(this.elements);
    this.elements = this.mdbTable.getDataSource();
    this.previous = this.mdbTable.getDataSource();
  }

  private _process(provisions) : void {
    provisions.forEach(p=>{
      p._scenario = this.scenarios.filter(s => s.name === p.scenario);
      this._provisionsService.timeRunning(p);
    });
    if ( this.elements.length === 0 ) {
      this.elements = provisions;
    } else {
      this.elements.forEach( function(p, index, object) {
        let found = provisions.filter(a=>a._id.toString() === p._id.toString());
        if ( found.length ) {
          p.status = found[0].status;
          p.statusVms = found[0].statusVms;
          p.isDestroyed = found[0].isDestroyed;
          p.outputs = found[0].outputs;
          p.destroy = found[0].destroy;
          this._provisionsService.timeRunning(p);
        } else {
          object.splice(index, 1);
        }   
      }.bind(this));

      provisions.forEach(function(p) {
        let found = this.elements.filter(a=>a._id.toString() === p._id.toString());
        if (found.length === 0){
          this.elements.unshift(p);
        }
      }.bind(this));
    }

    this._initElements();

  }

  ngOnInit() {

    var scenariosSub = this._scenariosService.getScenariosAll().subscribe( res => {
      scenariosSub.unsubscribe();  
      this.scenarios = res.results;
      
      /*this.subscription = timer(0, 8000).pipe( switchMap(() => this._provisionsService.getProvisionsAdmin(this.filterParams) ) ).subscribe(provisions => { 
        this._process(provisions.results);  
      });*/

      this.refreshData();
      
    });

    //this._initElements();
  }


  ngOnDestroy() {
    if ( this.subscription ) {
      this.subscription.unsubscribe();
    }
  }

  ngAfterViewInit() {
    if ( this.mdbTablePagination ) {
      this.mdbTablePagination.setMaxVisibleItemsNumberTo(this.maxVisibleItems);

      this.mdbTablePagination.calculateFirstItemIndex();
      this.mdbTablePagination.calculateLastItemIndex();
      this.cdRef.detectChanges();
    }
  }

  searchItems() {
    const prev = this.mdbTable.getDataSource();

    if (!this.searchText) {
      this.mdbTable.setDataSource(this.previous);
      this.elements = this.mdbTable.getDataSource();
    }

    if (this.searchText) {
      this.elements = this.mdbTable.searchLocalDataBy(this.searchText);
      this.mdbTable.setDataSource(prev);
    }

    if ( this.mdbTablePagination ) {
      this.mdbTablePagination.calculateFirstItemIndex();
      this.mdbTablePagination.calculateLastItemIndex();

      this.mdbTable.searchDataObservable(this.searchText).subscribe(() => {
        this.mdbTablePagination.calculateFirstItemIndex();
        this.mdbTablePagination.calculateLastItemIndex();
      });
    }
  }

  showLogs($event, provision, type): void {
    $event.preventDefault();
    $event.stopPropagation();
    this.logstype = type;
    this.logShow = false;
    this.selectedprov = provision;
    this.logShow = true;
  }

  onLogsClose(): void {
    this.selectedprov = null;
    this.logShow = false;
  }

  openConfirmStartModal(provision) {
    var modalRef = this.modalService.show(ModalConfirmComponent, {
      class: 'modal-sm modal-notify modal-info',
      containerClass: '',
      data: {
        info: {
          title: 'Confirm Start VMs?',
          icon: 'play',
          buttonColor: 'grey'
        }
      }
    } );

    var sub = modalRef.content.action.subscribe( (result: any) => { 
      sub.unsubscribe();
      this._startVms(provision);
    });
  }

  private _startVms(provision): void {
    var sub = this._provisionsService.startVms(provision._id.toString(), provision.user._id).subscribe( res => {
      provision.startVms = res.startVms;
      sub.unsubscribe();
      this._alertService.showAlert({
        type: 'alert-primary', 
        text: `Starting all VMs for scenario '${provision.scenario}'...`
      });
    })
  }

  openConfirmStopModal(provision) {
    var modalRef = this.modalService.show(ModalConfirmComponent, {
      class: 'modal-sm modal-notify modal-info',
      containerClass: '',
      data: {
        info: {
          title: 'Confirm Stop VMs?',
          icon: 'stop',
          buttonColor: 'grey'
        }
      }
    } );

    var sub = modalRef.content.action.subscribe( (result: any) => { 
      sub.unsubscribe();
      this._stopVms(provision);
    });
  }

  private _stopVms(provision): void {
    var sub = this._provisionsService.stopVms(provision._id.toString(), provision.user._id).subscribe( res => {
      provision.startVms = res.startVms;
      sub.unsubscribe();
      this._alertService.showAlert({
        type: 'alert-primary', 
        text: `Stopping all VMs for scenario '${provision.scenario}'...`
      });
    })
  }

  openInfoModal(provision) {
    this.modalService.show(ModalInfoComponent, {
      backdrop: true,
      keyboard: true,
      focus: true,
      show: false,
      ignoreBackdropClick: false,
      class: 'modal-lg',
      containerClass: '',
      animated: true,
      data: {
        info: provision
      }
    } );
  }

  openConfirmDestroyModal(provision) {
    var modalRef = this.modalService.show(ModalConfirmComponent, {
      class: 'modal-sm modal-notify modal-danger',
      containerClass: '',
      data: {
        info: {
          title: 'Confirm destroy this provision?',
          icon: 'times-circle'
        }
      }
    } );

    var sub = modalRef.content.action.subscribe( (result: any) => { 
      sub.unsubscribe();
      this._provisionsService.newDestroy(provision._id.toString(), provision.user._id).subscribe( provUpdated => {
        this._alertService.showAlert({
          type: 'alert-primary', 
          text: `Provision of scenario '${provision.scenario}' is going to be destroyed`
        });
        provision.destroy = provUpdated.destroy;
      })
    });
  }

  openConfirmDeleteModal(provision) {
      var modalRef = this.modalService.show(ModalConfirmComponent, {
        class: 'modal-sm modal-notify modal-danger',
        containerClass: '',
        data: {
          info: {
            title: 'Confirm delete?',
            icon: 'trash-alt'
          }
        }
    } );

    var sub = modalRef.content.action.subscribe( (result: any) => { 
      sub.unsubscribe();
      this._provisionsService.delProvision(provision._id, provision.user._id).subscribe( res => {
        this.elements = this.elements.filter(e=>{
          return e._id.toString() !== provision._id.toString();
        });
        this._initElements();
        this._alertService.showAlert({
          type: 'alert-primary', 
          text: `Provision entry '${provision.scenario}' was deleted`
        });
      });
    });
  }

  refreshData() { 
    this.elements = [];
    this.loading = true;
    this.searchText = "";
    var instantSubs = this._provisionsService.getProvisionsAdmin(this.filterParams).subscribe( provisions=>{
      instantSubs.unsubscribe();
      this.loading = false;  
      this._process(provisions.results);    
    });
  }

  onCheckValue() : void {
    this.filterParams = {};
    if ( !this.filter.showDestroyed ) {
      this.filterParams.isDestroyed = false;
    }
    this.refreshData();
  }

  openConfirmExtendModal(provision) {
    var modalRef = this.modalService.show(ModalConfirmComponent, {
      class: 'modal-sm modal-notify modal-info',
      containerClass: '',
      data: {
        info: {
          title: `Extend running VMs for ${this._provisionsService.RUNNING_PERIOD} days?`,
          icon: 'plus-square',
          buttonColor: 'grey'
        }
      }
    } );

    var sub = modalRef.content.action.subscribe( (result: any) => { 
      sub.unsubscribe();

      this._provisionsService.extend(provision._id.toString(), provision.user._id).subscribe( res => {
        provision.countExtend = res.countExtend;
        provision.timeRunning = res.timeRunning;
        provision.runningFrom = res.runningFrom;
        this._provisionsService.timeRunning(provision);
        this._alertService.showAlert({
          type: 'alert-primary', 
          text: `Running period extended another ${this._provisionsService.RUNNING_PERIOD} days (from now) for provision '${provision.scenario}'`
        });
      })
    });
  }

}