import { Component, OnInit } from '@angular/core';
import { ProvisionsService } from '../services/provisions.service'; 
import { Subscription, timer} from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { AuthGuard } from '../services/auth.guard';
import { AlertService } from '../services/alert.service';
import { MDBModalService } from 'angular-bootstrap-md';
import { ModalInfoComponent } from '../modals/modalinfo.component';
import { ModalConfirmComponent } from '../modals/confirm.component';
import { ProvisionModalComponent } from '../modals/edit-provision.component';


@Component({
  selector: 'app-provisions',
  templateUrl: './provisions.component.html',
  styleUrls: ['./provisions.component.scss'],
  providers: [ProvisionsService]
})
export class ProvisionsComponent implements OnInit {

  private _userId;
  provisions;
  destroys;
  subscription: Subscription;
  instantSubs: Subscription;
  logShow: boolean = false;
  logstype: String = 'provision';
  public selectedprov: Object = null;
  history: Boolean = false;
  
  constructor(private modalService: MDBModalService, private _alertService: AlertService, private _provisionsService: ProvisionsService, private _auth: AuthGuard) {
    this._auth.getUserInfo().subscribe( value => {
      this._userId = value? value._id : null;
    });
  }

  private _refresh(): void {
    this.instantSubs = this._provisionsService.getProvisionsByUser(this._userId).subscribe( provisions=>{
      provisions = provisions.results;
      this.provisions = provisions.filter(p => !p.destroy || !p.destroy.status || p.destroy.status !== 'destroyed');
      this.destroys = provisions.filter(p => p.destroy && p.destroy.status === 'destroyed');
      this.instantSubs.unsubscribe();
    })
  }

  ngOnInit() {    
    this.subscription = timer(0, 8000).pipe( switchMap(() => this._provisionsService.getProvisionsByUser(this._userId) ) ).subscribe(provisions => { 
      provisions = provisions.results;
      this.provisions = provisions.filter(p => !p.destroy || !p.destroy.status || p.destroy.status !== 'destroyed');
      this.destroys = provisions.filter(p => p.destroy && p.destroy.status === 'destroyed');
      
      if ( this.provisions && this.provisions.length === 0 ) {
        this.subscription.unsubscribe();
      }

    })
  }

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

  setModal(provision, frame) : void {
    frame.show();
    this._provisionsService.setSelectedProv(provision);
  }


  del(provision): void {
    this._provisionsService.delProvision(provision._id.toString(), this._userId).subscribe( res => {
      this._refresh();
      this._alertService.showAlert({
        type: 'alert-dark', 
        text: `Provision entry <b>${provision.scenario}</b> was deleted from your history`
      });
    })
  }

  toggleHistory(): void {
    this.history = !this.history;
  }

  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(), this._userId).subscribe( res => {
        this._refresh();
        this._alertService.showAlert({
          type: 'alert-dark', 
          text: `Provision of scenario <b>${provision.scenario}</b> is going to be destroyed.`
        });
      });
    });
  }

  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'
        },
        provision: provision
      }
    } );

    var sub = modalRef.content.action.subscribe( (result: any) => { 
      console.log("Confirm result", result);
      sub.unsubscribe();
      this._provisionsService.stopVms(provision._id.toString(), this._userId, result).subscribe( res => {
        provision.statusVms = res.statusVms;
        provision.timeRunning = res.timeRunning;
        provision.runningFrom = res.runningFrom;
        this._alertService.showAlert({
          type: 'alert-dark', 
          text: `Stopping all VMs for scenario <b>${provision.scenario}</b>...`
        });
      })
    });
  }

  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'
        },
        provision: provision
      }
    } );

    var sub = modalRef.content.action.subscribe( (result: any) => { 
      sub.unsubscribe();
      this._provisionsService.startVms(provision._id.toString(), this._userId).subscribe( res => {
        provision.statusVms = res.statusVms;
        provision.timeRunning = res.timeRunning;
        provision.runningFrom = res.runningFrom;
        this._alertService.showAlert({
          type: 'alert-dark', 
          text: `Starting all VMs for scenario <b>${provision.scenario}</b>...`
        });
      })
    });
  }


  openConfirmExtendModal($event, provision) {
    $event.preventDefault();
    var modalRef = this.modalService.show(ModalConfirmComponent, {
      class: 'modal-sm modal-notify modal-info',
      containerClass: '',
      data: {
        info: {
          title: `Renew 24x7 period?`,
          icon: 'redo-alt',
          buttonColor: 'grey'
        }
      }
    } );

    var sub = modalRef.content.action.subscribe( (result: any) => { 
      sub.unsubscribe();
      this._provisionsService.extend(provision._id.toString(), this._userId).subscribe( res => {
        provision.countExtend = res.countExtend;
        provision.timeRunning = res.timeRunning;
        provision.runningFrom = res.runningFrom;
        this._alertService.showAlert({
          type: 'alert-dark', 
          text: `Running period extended another ${provision._scenarioDoc.allowed24x7RunningDays} days (from now) for provision <b>${provision.scenario}</b>`
        });
      });
    });
  }

  openScheduleModal(provision) {
    var modalRef = this.modalService.show(ProvisionModalComponent, {
      class: 'modal-lg modal-notify',
      containerClass: '',
      data: {
        provision: provision
      }
    } );

    var sub = modalRef.content.action.subscribe( (data: any) => { 
      sub.unsubscribe();
      
      console.log("openScheduleModal returns", data);
    });
  }

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

  openModal(provision) {
    this.modalService.show(ModalInfoComponent, {
      class: 'modal-lg',
      containerClass: '',
      data: {
        info:provision
      }
    } );
  }

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

  onStartProvision(scenario): void {
    this._alertService.showAlert({
      type: 'alert-dark', 
      text: `Scenario <b>${scenario.name}</b> is going to be provisioned. Scroll up to your Provisions to watch out progress.`
    });
    this._refresh();
  }

}
