import { Injectable } from '@angular/core';
import { SandboxSetupProcessWorkSpace, state, ResponseSetupWorkSpace } from 'app/models/sandbox-progress.model';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import { AuthService } from 'app/services/auth.service';
import { LocalStorageService } from 'angular-2-local-storage';



@Injectable()
export class ProgressStateSetupWorkspaceService {



  public setupProcessWorked = new BehaviorSubject<SandboxSetupProcessWorkSpace>({ show: false, state: state.NONE, data: { createdTime: Date.now() } });
  public ProgressIconComponent = new BehaviorSubject<{ state, counter: number }>({ state: state.NONE, counter: 0 });

  constructor(private authService: AuthService, protected localStorageService: LocalStorageService, ) {
    const empData = this.localStorageService.get('userInfo');

    Observable.fromPromise(this.authService.getWorkspaceId({ adId: empData['adId'] }))
    .subscribe(res => {
      if (res.status !== 'error') {
        const resCast = JSON.parse(res['data']) as ResponseSetupWorkSpace;
        const timeFromCreated = this.calculateTimeFromCreated(resCast.createdTime);
        this.setupProcessWorked.next({
          data: resCast,
          show: resCast.status.toUpperCase() !== 'TERMINATED', // && ,
          state: resCast.status.toUpperCase() !== 'TERMINATED' ? timeFromCreated < 30 ? state.InProgress : state.Completed : state.NONE
        });
      }
    });
  }

  public calculateTimeFromCreated(createdTime: number): number {
    return (Date.now() - createdTime) / (1000 * 60);
  }

}
