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

import * as moment from 'moment-timezone';


@Component({
  selector: 'qmi-new-provision',
  templateUrl: './new-provision.component.html',
  styleUrls: ['./new-provision.component.scss']
})
export class NewProvisionConfirmComponent implements OnInit, OnDestroy {
  
  scenario;
  action: Subject<any> = new Subject();
  shortDesc: string;
  sendData : any = {
    description: "",
    servers: null,
    region: null,
    isExternalAccess: false
  };
  selectedProductVersion: any = {};
  selectedVmType: any = {};
  selectedNodeCount: any = {};
  selectedDiskSizeGb: any = {};
  vmTypesSub: Subscription;
  vmTypes: any;
  servers: any = {};
  schedule: any = {
    is24x7: false,
    isStartupTimeEnable: false,
    startupTime: {
      "hour": 7,
      "minute": 0
    },
    shutdownTime: {
      "hour": 20,
      "minute": 0
    }
  };
  selectedServers: any = {};
  availableDiskSizes = {};

  selectedDeployOpts = "";

  zone;
  forms;

  constructor( public modalRef: MDBModalRef, private _scenariosService: ScenariosService, private _provisionsService: ProvisionsService ) {}

  ngOnInit() {
    this.zone = moment.tz.guess(true);

    this.forms = document.getElementsByClassName('needs-validation');


    this.vmTypesSub = this._scenariosService.getScenarioVmtypes().subscribe ( res => {
      this.vmTypes = res.results.filter(v=>!v.disabled);

      if ( this.scenario.availableProductVersions.length ) {
        this.scenario.availableProductVersions.forEach(server => {
            
          if (server.vmTypeDefault) {
              this.selectedVmType[server.index] = server.vmTypeDefault;
              this.selectedDiskSizeGb[server.index] =  server.diskSizeGbDefault? parseInt(server.diskSizeGbDefault) : 500;
              this.availableDiskSizes[server.index] = [128,250,500,750,1000].filter(function(size) {
                return size >= this.selectedDiskSizeGb[server.index];
              }.bind(this));
          }

          if ( server.nodeCount ) {
              this.selectedNodeCount[server.index] = server.nodeCount;
          }

            
          

          if ( server.versions && server.versions.length ) {
            let lastIndex = server.versions.length - 1;
            this.selectedProductVersion[server.index] = server.productVersionDefault? server.productVersionDefault : server.versions[lastIndex].name;
          }
            
          this.selectedServers[server.index] = server.optionalDefault !== undefined && server.optional !== null? server.optionalDefault : true;  

        });

        //if ( this.scenario.deployOpts && this.scenario.deployOpts.length ) {
        //  this.selectedDeployOpts = this.scenario.deployOpts[0]._id;
        //}
      }
      
      this.vmTypesSub.unsubscribe();
    })
  }


  ngOnDestroy() { 
    
  }

  confirm() : void {

      if (!this.sendData.description || this.sendData.description.trim() === "" || !this.selectedDeployOpts || this.selectedDeployOpts === "" ) {
          this.forms[0].classList.add('was-validated');
          return;
      }
      this.sendData.servers = {};
      this.sendData.deployOpts = this.selectedDeployOpts;
      console.log("this.selectedServers", this.selectedServers);
      for (let key in this.selectedServers) {
        
        if (!this.sendData.servers[key]) {
          this.sendData.servers[key] = {};
        }
      
        if ( this.selectedServers[key] === false ) {
          this.sendData.servers[key].disabled = true;
        } else {
          this.sendData.servers[key].disabled = false;
          
          if ( this.selectedDiskSizeGb[key] ) {
            this.sendData.servers[key].diskSizeGb = this.selectedDiskSizeGb[key];
          }
          if (this.selectedVmType[key]) {
            this.sendData.servers[key].vmType = this.selectedVmType[key];
          }
          if ( this.selectedNodeCount[key] ) {
            this.sendData.servers[key].nodeCount = this.selectedNodeCount[key];
          }

          this.scenario.availableProductVersions.forEach(server => {
            if ( server.versions ) {
              server.versions.forEach(v=> {
                if (v.name === this.selectedProductVersion[key]){
                  this.sendData.servers[key].version = v;
                }
              });
            }
          });

        }
        
        
      }
      if ( this.scenario.isDivvyEnabled ) {
        if ( !this.schedule.is24x7 ) {
          let scheduleUTC = this._provisionsService.getUTCTimes(this.schedule, this.zone);
          this.sendData.scheduleData = {
            is24x7: false,
            isStartupTimeEnable: this.schedule.isStartupTimeEnable,
            utcTagStartupTime: scheduleUTC.tagStartup,
            utcTagShutdownTime: scheduleUTC.tagShutdown,
            localeStartupTime: this.schedule.startupTime.hour+":"+this._provisionsService.addZero(this.schedule.startupTime.minute),
            localeShutdownTime: this.schedule.shutdownTime.hour+":"+this._provisionsService.addZero(this.schedule.shutdownTime.minute),
            localTimezone: scheduleUTC.timezone,
            timezoneOffset: scheduleUTC.timezoneOffset
          }
        } else {
          this.sendData.scheduleData = {
            is24x7: true
          }
        }
      }
      
      console.log("sendData", this.sendData);
      this.action.next(this.sendData);
      this.modalRef.hide();
  }

  checkOnchange($event) {
    this.sendData.isExternalAccess = $event.checked;
  }

  checkOnchangeSchedule($event) {
    this.schedule.is24x7 = $event.checked;
  }

  checkOnchangeStartupTime($event) {
    this.schedule.isStartupTimeEnable = $event.checked;
  }

  checkOnchangeServer($event, server) {
    this.selectedServers[server.index] = $event.checked;
  }

  getUTCTimes() {
    return this._provisionsService.getUTCTimes(this.schedule, this.zone);
  }

}