import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable()
export class UserListService implements Resolve<any> {

  userList: any[];
  onUserListChanged: BehaviorSubject<any>;

  /**
   * Constructor
   *
   * @param {HttpClient} _httpClient
   */
  constructor(
    private _httpClient: HttpClient
  ) {
    // Set the defaults
    this.onUserListChanged = new BehaviorSubject({});
  }

  /**
   * Resolver
   *
   * @param {ActivatedRouteSnapshot} route
   * @param {RouterStateSnapshot} state
   * @returns {Observable<any> | Promise<any> | any}
   */
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any {
    return new Promise((resolve, reject) => {

      Promise.all([
        this.getUserList()
      ]).then(
        () => {
          resolve();
        },
        reject
      );
    });
  }

  /**
   * Get user list
   *
   * @returns {Promise<any>}
   */
  getUserList(): Promise<any> {
    return new Promise((resolve, reject) => {
      this._httpClient.get('api/users-list')
        .subscribe((response: any) => {
          this.userList = response;
          this.onUserListChanged.next(this.userList);
          resolve(response);
        }, reject);
    });
  }
}
