import { Component, OnInit, Input } from '@angular/core';
import { Observable } from 'rxjs';

// const url = require('file!img!./loading.gif');

import { LoadingInfoState } from './loading-info-state';

@Component({
  selector: 'loading-info',
  template: require('./loading-info.component.html'),
  styles:   [require('./loading-info.component.scss')]
})
export class LoadingInfoComponent implements OnInit {
  private static instances               = {};
  @Input() id: string;
                 state: LoadingInfoState = LoadingInfoState.NORMAL;
                 loadingInfoState        = LoadingInfoState;

  static startLoading(id: string) {
    setTimeout(() => {
      let d: LoadingInfoComponent = LoadingInfoComponent.instances[id];
      if (d !== undefined) d.state = LoadingInfoState.LOADING;
    });
  }


  static stopLoading(id: string) {
    let d: LoadingInfoComponent = LoadingInfoComponent.instances[id];
    d.state                     = LoadingInfoState.NORMAL;
  }

  static setOn(id: string, o: Observable<any>) {
    let d: LoadingInfoComponent = LoadingInfoComponent.instances[id];
    if (d === undefined) {
      console.error(`LoadinInfoCmp, setOn: '${id}' is undefinded`);
      return;
    }
    d.state = LoadingInfoState.LOADING;
    o.subscribe(() => {
      d.state = LoadingInfoState.NORMAL;
    }, () => {
      d.state = LoadingInfoState.NORMAL;
    });
  }


  constructor() {

  }

  ngOnInit() {
    if (!this.id) this.state = LoadingInfoState.LOADING;
    LoadingInfoComponent.instances[this.id] = this;
  }

}
