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

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

  getAssignedUserSpaces() {
    return this.apollo
      .query<{ assignedUserSpaces: QueryResult<UserSpace> }>({
        query: gql`
          query getAssignedUserSpaces {
            assignedUserSpaces {
              nodes {
                id
                name

                owner {
                  id
                  username
                }
              }
            }
          }
        `,
      })
      .pipe(map(result => result.data?.assignedUserSpaces.nodes));
  }

  onChange(): Observable<void> {
    return this.apollo
      .subscribe<{ groupChange: void }>({
        query: gql`
          subscription onUserSpaceChange {
            userSpaceChange
          }
        `,
      })
      .pipe(map(result => result.data?.groupChange));
  }

  delete(object: UserSpace): Observable<boolean> {
    return this.apollo
      .mutate<{ userSpace: { delete: boolean } }>({
        mutation: gql`
          mutation deleteUserSpace($id: Int!) {
            userSpace {
              delete(id: $id)
            }
          }
        `,
        variables: {
          id: object.id,
        },
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data?.userSpace.delete ?? false));
  }
}
