import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Role } from 'src/app/model/entities/role';
import { QueryResult } from 'src/app/model/entities/query-result';
import { Apollo, gql } from 'apollo-angular';
import { catchError, map } from 'rxjs/operators';
import { SpinnerService } from 'src/app/service/spinner.service';

@Injectable({
  providedIn: 'root',
})
export class CommonDataService {
  constructor(
    private spinner: SpinnerService,
    private apollo: Apollo
  ) {}

  getAllRoles(): Observable<Role[]> {
    return this.apollo
      .query<{ roles: QueryResult<Role> }>({
        query: gql`
          query getRoles {
            roles {
              nodes {
                id
                name
              }
            }
          }
        `,
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data.roles.nodes));
  }
}
