import { singleton } from 'aurelia-framework';
import { UIInternal } from '../../utils/ui-internal';

@singleton(false)
export class GlobalLoaderService {

  public text: string;
  public allowToShowGlobalLoader = false;
  public delay: number;
  public forceShow = false;

  /**
   * Allow to show the Global Loader for the next api request. 
   *
   * @param {(boolean | string)} value: true to show, or a string to show a message with.
   * @param {number} [delay=null] = the delay in ms before the loader appears.
   * @memberof GlobalLoaderService
   */
  public allow(value: boolean | string = true, delay: number = null): void {
    if (typeof value == 'boolean') {
      this.allowToShowGlobalLoader = value;
    } else if (typeof value == 'string') {
      this.text = value;
      this.allowToShowGlobalLoader = true;
    } else {
      this.text = null;
      this.allowToShowGlobalLoader = true;
    }

    this.delay = delay;
  };

  public reset(): void {
    if (this.forceShow == false) {
      this.allowToShowGlobalLoader = false;
      this.text = null;
      this.delay = null;
    }
  }

  public show(value: boolean | string = true, delay: number = null): void {
    this.allow(value, delay);
    this.forceShow = true;
    UIInternal.broadcast(UIInternal.EVT_GLOBAL_LOADER_SHOW);
  }

  public hide(): void {
    this.forceShow = false;
    this.reset();
    UIInternal.broadcast(UIInternal.EVT_GLOBAL_LOADER_HIDE);
  }
}
