'use strict';
export default class SystemService {

  static _instance;

  _pollPromise;
  _pollSuccessCallback;
  _pollInterval;

  static create($http, $timeout, config, authService) {
    this._instance = new this($http, $timeout, config, authService);
    return this._instance;
  }

  static getInstance() {
    return this._instance;
  }

  constructor(private $http,
    private $timeout,
    private config,
    private authService
  ){}

  
() {
    return this._doRestart();
  }

  checkForLife(successCallback, pollInterval, initialInterval) {
    this._startPollUserInfo(successCallback, pollInterval, initialInterval);
  }

  fetchHQ() {
    const api = this.config.root + 'api/rest/hq';
    return this.$http.get(api, { withCredentials: true, cache: false }).then(res => {
      return res.data;
    });
  }

  private _doRestart() {
    const restartAPI = 'api/rest/system/restart';
    return this.$http({
      method: 'POST',
      url: this.config.root + restartAPI,
      headers: {'Content-Type': 'application/json'}
    });
  }

  private _startPollUserInfo(successCallback, interval, initialInterval) {
    const pollUserInfo = () => this._pollUserInfo();
    initialInterval = initialInterval || interval;
    this._pollSuccessCallback = successCallback;
    this._pollInterval = interval;
    this._nextPoll(pollUserInfo, initialInterval);
  }

  private _pollUserInfo() {
    const pollUserInfo = () => this._pollUserInfo();
    this.authService.getUserInfo().then( (resp) => {
      if (!resp) {
        this._nextPoll(pollUserInfo, this._pollInterval);
      } else {
        this._pollSuccessCallback();

        this._pollPromise = undefined;
        this._pollInterval = undefined;
        this._pollSuccessCallback = undefined;
      }
    }).catch( () => {
      this._nextPoll(pollUserInfo, this._pollInterval);
    });
  };

  private _nextPoll(pollCallback, interval) {
    interval = interval || 1000;

    this.$timeout.cancel(this._pollPromise);
    this._pollPromise = this.$timeout(pollCallback, interval);
  }
}

doRestart