import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment.prod';

import * as moment from 'moment';


@Injectable({
  providedIn: 'root'
})
export class ProvisionsService {

  selectedProv;
  RUNNING_PERIOD : number = 4;
  STOP_PERIOD : number = 20;

  constructor( private httpClient: HttpClient ) { }

  getProvisionsAdmin( filter : any ) : Observable<any> {
    // Initialize Params Object
    let params = new HttpParams();
    if ( filter ){
      params = params.append("filter", JSON.stringify(filter));
    } 
    return this.httpClient.get(`${environment.apiVersionPath}/provisions`, { params: params });
  }

  getProvisionsByUser(userId) : Observable<any> {
    return this.httpClient.get(`${environment.apiVersionPath}/users/${userId}/provisions`);
  }

  getDestroyProvisionsAdmin() : Observable<any> {
    return this.httpClient.get(`${environment.apiVersionPath}/destroyprovisions`);
  }


  newProvision(body, userId) : Observable<any> {
    return this.httpClient.post(`${environment.apiVersionPath}/users/${userId}/provisions`, body);
  }

  delProvision(id, userId):  Observable<any> {
    return this.httpClient.delete(`${environment.apiVersionPath}/users/${userId}/provisions/${id}`);
  }

  newDestroy(id, userId) : Observable<any> {
    return this.httpClient.post(`${environment.apiVersionPath}/users/${userId}/provisions/${id}/destroy`, null);
  }

  getDestroyProvisions(userId) : Observable<any> {
    return this.httpClient.get(`${environment.apiVersionPath}/users/${userId}/destroyprovisions`);
  }

  /*
  getCombinedProvisions(userId): Observable<any> {
    return forkJoin(this.getProvisionsByUser(userId), this.getDestroyProvisions(userId))
  }

  getCombinedProvisionsAdmin(): Observable<any> {
    return forkJoin(this.getProvisionsAdmin(), this.getDestroyProvisionsAdmin())
  }*/


  getProvisionLogs(id) : Observable<any> {
    return this.httpClient.get(`${environment.apiVersionPath}/provisions/${id}/logs`, {responseType: 'text'});
  }

  getDestroyLogs(id) : Observable<any> {
    return this.httpClient.get(`${environment.apiVersionPath}/destroyprovisions/${id}/logs`, {responseType: 'text'});
  }

  stopVms(id, userId): Observable<any> {
    return this.httpClient.post(`${environment.apiVersionPath}/users/${userId}/provisions/${id}/deallocatevms`, null);
  }

  startVms(id, userId): Observable<any> {
    return this.httpClient.post(`${environment.apiVersionPath}/users/${userId}/provisions/${id}/startvms`, null);
  }

  extend(id, userId): Observable<any> {
    return this.httpClient.post(`${environment.apiVersionPath}/users/${userId}/provisions/${id}/extend`, null);
  }

  setSelectedProv(provision : any) : void {
    if ( provision ) {
      this.selectedProv = provision;
    } else {
      this.selectedProv = null;
    }
  }

  getSelectedProv() : any {
    return this.selectedProv;
  }

  timeRunning(p) : void{
    if (!p.statusVms) {
      return;
    }
    let now = new Date();
    let runningFromTime = p.runningFrom? new Date(p.runningFrom).getTime() : new Date(p.created).getTime();
    let totalRunningTime = p.timeRunning*1000*60;

    if (p.statusVms !== 'Stopped' && p.statusVms !== 'Starting' && !p.isDestroyed) {
      totalRunningTime = totalRunningTime + Math.abs(now.getTime() - runningFromTime);
    }
    
    let authShutdownDate = new Date(runningFromTime);
    authShutdownDate.setDate(authShutdownDate.getDate()+this.RUNNING_PERIOD);
    let autoshutDown = authShutdownDate.getTime() - now.getTime();
    
    let durationAutoShutdown = moment.duration(autoshutDown);
    let duration = moment.duration(totalRunningTime);
    p.runningDays = Math.floor(duration.asDays());
    p.runningHours = duration.hours();
    p.runningMinutes = duration.minutes();
    p.autoshutdownDays = Math.floor(durationAutoShutdown.asDays());
    p.autoshutdownHours = durationAutoShutdown.hours();
    p.autoshutdownMinutes = durationAutoShutdown.minutes();


    if ( (p.statusVms === 'Stopped' || p.statusVms === 'Starting') && !p.isDestroyed ) {
      let autoDestroyDate = new Date(p.stoppedFrom);
      autoDestroyDate.setDate(autoDestroyDate.getDate() + this.STOP_PERIOD);
      let autoDestroy = autoDestroyDate.getTime() - now.getTime();
      let durationStop = moment.duration(autoDestroy);
      p.autoDestroyDays = Math.floor(durationStop.asDays());
      p.autoDestroyHours = durationStop.hours();
      p.autoDestroyMinutes = durationStop.minutes();

      let inactiveDate = new Date(p.stoppedFrom);
      let inactive = Math.abs(inactiveDate.getTime() - now.getTime());
      let durationInactive = moment.duration(inactive);
      p.inactiveDays = Math.floor(durationInactive.asDays());
      p.inactiveHours = durationInactive.hours();
      p.inactiveMinutes = durationInactive.minutes();
    }
    
  }

}
