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 { ScenariosService } from '../services/scenarios.service';
import { AlertService } from '../services/alert.service';
import { MDBModalService } from 'angular-bootstrap-md';
import { ModalInfoComponent } from '../modals/modalinfo.component';
import { ModalConfirmComponent } from '../modals/confirm.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;
  scenariosSub: Subscription;
  logShow: boolean = false;
  logstype: String = 'provision';
  public selectedprov: Object = null;
  scenarios;
  
  constructor(private modalService: MDBModalService, private _alertService: AlertService, private _provisionsService: ProvisionsService, private _scenariosService: ScenariosService, 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;   
      provisions.forEach(p=>{
        p._scenario = this.scenarios.filter(s => s.name === p.scenario);
        this._provisionsService.timeRunning(p);
      });
      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.scenariosSub = this._scenariosService.getScenariosAll().subscribe( res => {

      this.scenarios = res.results;
      this.scenariosSub.unsubscribe();
      
      this.subscription = timer(0, 8000).pipe( switchMap(() => this._provisionsService.getProvisionsByUser(this._userId) ) ).subscribe(provisions => { 
        provisions = provisions.results;
        provisions.forEach(p=>{
          p._scenario = this.scenarios.filter(s => s.name === p.scenario);
          this._provisionsService.timeRunning(p);
        });
        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');
      })
    }); 
  }

  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-primary', 
        text: `Provision entry '${provision.scenario}' was deleted from your 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-primary', 
          text: `Provision of scenario '${provision.scenario}' 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'
        }
      }
    } );

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

  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._provisionsService.startVms(provision._id.toString(), this._userId).subscribe( res => {
        provision.statusVms = res.statusVms;
        provision.timeRunning = res.timeRunning;
        provision.runningFrom = res.runningFrom;
        this._provisionsService.timeRunning(provision);
        this._alertService.showAlert({
          type: 'alert-primary', 
          text: `Starting all VMs for scenario '${provision.scenario}'...`
        });
      })
    });
  }


  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(), this._userId).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}'`
        });
      });
    });
  }

  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-primary', 
      text: `Scenario '${scenario.name}' is going to be provisioned. Scroll up to your Provisions to watch out progress.`
    });
    this._refresh();
  }

}
