import { Component, OnInit, OnDestroy } from '@angular/core';
import { MDBModalRef } from 'angular-bootstrap-md';
import { Subject, Subscription } from 'rxjs';
import { ScenariosService } from '../services/scenarios.service';
import { SubscriptionsService } from '../services/deployopts.service';

@Component({
  selector: 'qmi-new-scenario',
  templateUrl: './edit-scenario.component.html',
  styleUrls: ['./edit-scenario.component.scss']
})
export class ScenarioModalComponent implements OnInit, OnDestroy {
  
  scenario;
  action: Subject<any> = new Subject();
  subscriptions;
  selectedSubscription;

  sendData : any = {
    availableProductVersions: [{
      product: 'String: <ie: Qlik Sense>',
      vmTypeDefault: 'String: <i.e: Standard_D8s_v3>',
      diskSizeGbDefault: 'Integer: <values: 128,250,500,750,1000>',
      index: 'vm1',
      versions: []
    }]
  };
 
  constructor( public modalRef: MDBModalRef, private _scenariosService: ScenariosService, private _subscriptionsService: SubscriptionsService ) {}

  ngOnInit() {
      this._subscriptionsService.getSubscriptions().subscribe ( res => {
        this.subscriptions = res.results;
        console.log("SCENARIO",this.scenario);
        if (this.scenario) {
          this.sendData = JSON.parse(JSON.stringify(this.scenario))
        }
        console.log("sendData",this.sendData);
        
        if (this.scenario.subscription ) {
          this.selectedSubscription = this.scenario.subscription._id;
        } else {
          this.selectedSubscription = res.results[0]._id;
        }  
      });
  }

  ngOnDestroy() { 
    
  }

  confirm() : void {
      
      this.sendData.subscription = this.selectedSubscription;
      console.log("sendData", this.sendData);
      //this.action.next(this.sendData);
      if ( this.sendData._id) {
        var id = this.sendData._id.toString();
        this.sendData._id = undefined;
        this._scenariosService.updateScenario(id, this.sendData).subscribe( res=> {
          console.log("done", res);
          this.action.next("DONE!!!");
          this.modalRef.hide();
        });
      } else {
        this._scenariosService.addScenario(this.sendData).subscribe( res=> {
          console.log("done", res);
          this.action.next("DONE!!!");
          this.modalRef.hide();
        });
      }
      
      
  }

  delete() : void {    
    this._scenariosService.deleteScenario(this.sendData._id).subscribe( res=> {
      console.log("done", res);
      this.action.next("DONE!!!");
      this.modalRef.hide();
    });   
  }

  checkOnchange($event, field) {
    console.log("Checked?", $event.checked);
    this.sendData[field] = $event.checked;
  }

  updateJson(event: any, property: string) {
    var editField = event.target.textContent.trim();
    try {
        var value = JSON.parse(editField);
        this.sendData[property] = value;

    } catch (e) {
        console.log("error json", e);
    }
  }
}