import { Component, Output, OnInit, EventEmitter, OnDestroy } from '@angular/core';
import { ProvisionsService } from '../services/provisions.service';
import { ScenariosService } from '../services/scenarios.service';
import { AuthGuard } from '../services/auth.guard';
import { Subscription } from 'rxjs';
import { NewProvisionConfirmComponent } from '../modals/new-provision.component';
import { MDBModalService } from 'angular-bootstrap-md';


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

  searchText : String;

  constructor(private modalService: MDBModalService, private _provisionsService: ProvisionsService, private _scenariosService: ScenariosService, private _auth: AuthGuard) { 
    this._auth.getUserInfo().subscribe( value => {
      this.user = value;
    });
  }

  @Output() onStartProvision = new EventEmitter<object>();

  user;
  scenarios;
  scenariosSub: Subscription;

  ngOnInit() {

    this.scenariosSub = this._scenariosService.getScenarios().subscribe( res => {
      this.scenarios = res.results;      
      this.scenariosSub.unsubscribe();
      console.log("scenarios", this.scenarios);
    });
  }

  ngOnDestroy() {}

  openNewProvisionConfirmModal(scenario) {
    var modalRef = this.modalService.show(NewProvisionConfirmComponent, {
      class: 'modal-md modal-notify',
      containerClass: '',
      data: {
        scenario: scenario
      }
    } );

    var sub = modalRef.content.action.subscribe( (data: any) => { 
      sub.unsubscribe();
      
      const postData = {
        scenario: scenario.name,
        description: data.description,
        isExternalAccess: data.isExternalAccess
      };

      if ( data.servers ) { 
          postData["vmImage"] = data.servers;
      }
  
      this._provisionsService.newProvision(postData, this.user._id).subscribe( res => {
        console.log("Done!", res);
        this.onStartProvision.emit(scenario);
      });

    });
  }

}
