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';
import { AlertService } from '../services/alert.service';
import { UsersService } from '../services/users.service';


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

  searchText : String;
  selectedAllowedUsers = "";

  constructor(private modalService: MDBModalService, private _provisionsService: ProvisionsService, private _usersService: UsersService, private _auth: AuthGuard, private _alertService: AlertService) { 
    this._auth.getUserInfo().subscribe( value => {
      this.user = value;
    });
  }

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

  user;
  scenarios;
  scenariosSub: Subscription;

  ngOnInit() {

    this.scenariosSub = this._usersService.getScenarios(this.user._id.toString()).subscribe( res => {
      this.scenarios = res.results;  
      this.scenarios.forEach(s=>{
        var text = 'Visible_to_these_users_only: Administrators; ';
        if (s.allowedUsers && s.allowedUsers.length > 0 ){
          s.allowedUsers.forEach(au=>{
            text += au.displayName +"; ";
          })
        }
        if ( s.support && s.support.length ) {
          s.supportEmails = s.support.join(",");
        }
        s.selectedAllowedUsersText = text;
      })    
      this.scenariosSub.unsubscribe();
      console.log("scenarios", this.scenarios);
    });
  }

  ngOnDestroy() {}

  openNewProvisionConfirmModal(scenario) {
    var modalRef = this.modalService.show(NewProvisionConfirmComponent, {
      class: 'modal-lg 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,
        deployOpts: data.deployOpts
      };

      if ( data.servers ) { 
          postData["vmImage"] = data.servers;
      }
      if (data.scheduleData) {
        postData["scheduleData"] = data.scheduleData;
      }
  
      this._provisionsService.newProvision(postData, this.user._id).subscribe( res => {
        console.log("Done!", res);
        this.onStartProvision.emit(scenario);
      }, data => {
        this._alertService.showAlert({
          type: 'alert-danger', 
          text: `${data.error.msg}`
        });
      });

    });
  }

}
